如果你用someInt(> 0)乘以低于1.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值之间的距离,因此断言确保highestLessThanOne确实是小于1.0的最大值)。
换句话说,你的行
Object element = elementArray[(int)(Math.random() * elementArray.length)];
永远不会产生ArrayIndexOutOfBoundsException。
此外,根据Mark Dickinsons的评论here,这也适用于乘以一个双。
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.)