最小的epsilon,以便比较结果发生变化

时间:2013-09-12 17:37:49

标签: java floating-point comparison

最小浮点值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

1 个答案:

答案 0 :(得分:3)

您可以尝试Math.nextUp(x)

这是doc:

  

返回正无穷大方向上与f相邻的浮点值。此方法在语义上等同于nextAfter(f,Float.POSITIVE_INFINITY);但是,nextUp实现可能比其等效的nextAfter调用运行得更快。

     

特例:

   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 
     

参数:

   f - starting floating-point value 
     

返回:

   The adjacent floating-point value closer to positive infinity.