java - 最小的epsilon使得比较结果改变

标签 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

最佳答案

您可以尝试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/

相关文章:

java - junit测试与真实源码混合情况下的POM文件

java - 如何从 Hibernate 5.2 中的带注释的类以编程方式生成数据库表

c++ - 可以将 'inf' 分配给变量,如 C++ 中的常规数值

f# - F# 中是否有任意精度 float ?像 BigFloat 这样的东西?

performance - 比较运算符性能(>、>=、<、<=)

c# - 如何使用 Salt 创建 SHA256 哈希?

binary - Verilog,与变量的不相等位进行比较

java - 通过<%@ include文件向jsp传递参数

java - 使用 ContributesAndroidInjector 提供 Activity

不依赖 FPU 舍入模式将 double 转换为 float