gpt4 book ai didi

java - 0.99999999999相乘时可以四舍五入到1.0吗?

转载 作者:IT老高 更新时间:2023-10-28 20:51:57 24 4
gpt4 key购买 nike

当一个非常接近 1 的 float 乘以 int > 0 时,它是否可以被解释为 1。

也就是说,如果 Math.random() 返回其可能的最高结果(比 1.0 低 1 步),将

(int)(Math.random() * 8)

是 8 还是 7?

举个实际的例子,这个经常使用的构造能否给出索引越界错误:

someArray[(int)(Math.random() * someArray.length)];

我对 Java 和 ActionScript 3 的答案特别感兴趣,但我想它们都使用相同的浮点运算规则,并且任何平台的答案都会很有用。

更新:虽然我已经接受了答案,但我仍然希望确认这在 ActionScript 3 中也不会出错,因为一位同事报告说他曾经看到它出错了部分促使我提出这个问题。

最佳答案

如果将低于 1.0 的最大值乘以 someInt (> 0),结果永远不会是someInt .

这可以针对这样的整数进行详尽的测试:

Double greatestLessThanOne = Double.longBitsToDouble(4607182418800017407L);

// Assert that greatestLessThanOne is indeed the largest double less than 1.
//assert 1.0 == greatestLessThanOne + Math.ulp(greatestLessThanOne);

for (int i = 1; i >= 0; i++)
if ((int) (greatestLessThanOne * i) == i)
System.out.println("Exception found: " + i);

片段不产生任何输出。

( Math.ulp 返回给定 double 值和下一个更大的 double 值之间的距离。因此,断言确保 greatestLessThanOne 确实是小于 1.0 的最大值。)

换句话说,你的线

Object element = elementArray[(int)(Math.random() * elementArray.length)];

永远不会引发 ArrayIndexOutOfBoundsException。


此外,根据 Mark Dickinsons 对 here 的评论, 这在与 double 相乘时也成立。

With IEEE 754 floating-point arithmetic in round-to-nearest mode, you can show that x * y < y for any x < 1.0 and any non-tiny positive y. (It can fail if y is either subnormal or the smallest positive normal number.)

关于java - 0.99999999999相乘时可以四舍五入到1.0吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7723746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com