最小浮点值 A 是多少,使得 (x < x + A) == true
?
我尝试使用 Float.MIN_VALUE 但令人惊讶的是(?[1])它不起作用(除了 0 值。)
知道 IEEE 754 标准如何存储浮点值后,我可以在相关浮点的尾数上加 1,但这确实很糟糕。我不想为了这样一件小事而在我的代码中放入字节数组和位操作,尤其是对于 Java。另外,如果我简单地向 Float.floatToIntBits() 加 1 并且尾数全为 1,它会将指数增加 1 并将尾数设置为 0。我不想实现这种情况的所有处理,如果它没有必要。
是否有某种函数(希望是内置的)给定 float x,它返回最小的 float A,使得 (x < x + A) == true
?
如果没有,最干净的实现方法是什么?
我使用它是因为我要迭代一行顶点
// return the next vertices strictly at the left of pNewX
float otherLeftX = pOppositeToCurrentCave.leftVertexTo(pNewX);
// we add MIN_VALUE so that the next call to leftVertexTo will return the same vertex returned by leftVertexTo(pNewX)
otherLeftX += Float.MIN_VALUE;
while(otherLeftX >= 0 && pOppositeToCurrentCave.hasLeftVertexTo(otherLeftX)) {
otherLeftX = pOppositeToCurrentCave.leftVertexTo(otherLeftX);
//stuff
}
现在由于这个问题,第一个顶点总是被跳过,因为第二次调用 leftVertexTo(otherLeftX)
返回的值与第一次调用时返回的值不同
[1] 并不奇怪。在注意到这个问题后我碰巧意识到,由于浮点之间的间隙是相对的,因此对于任何数字!= 0,MIN_VALUE 都很小,以至于它会被截断并且 (x = x + FLOAT.MIN_VALUE) == true
最佳答案
您可以尝试Math.nextUp(x)
这是文档:
Returns the floating-point value adjacent to f in the direction of positive infinity. This method is semantically equivalent to nextAfter(f, Float.POSITIVE_INFINITY); however, a nextUp implementation may run faster than its equivalent nextAfter call.
Special Cases:
If the argument is NaN, the result is NaN. If the argument is positive infinity, the result is positive infinity. If the argument is zero, the result is Float.MIN_VALUE
Parameters:
f - starting floating-point value
Returns:
The adjacent floating-point value closer to positive infinity.
关于java - 最小的epsilon使得比较结果改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770839/