Java 的 Math.IEEERemainder函数状态:
The remainder value is mathematically equal to f1 - f2 × n, where n is the mathematical integer closest to the exact mathematical value of the quotient f1/f2, and if two mathematical integers are equally close to f1/f2, then n is the integer that is even
对于以下内容:
double f1 = 0.1;
double f2 = 0.04;
System.out.println(Math.IEEEremainder(f1, f2));
输出为-0.019999999999999997
但是,0.1/0.04 = 2.5
与整数 2
和 3
等距。难道我们不应该在这里选择n = 2
,从而得到0.1 - 0.04*2 = 0.02
,而不是-0.02
吗?
最佳答案
参见:Is floating point math broken?
您可能认为 0.1/0.04
会准确返回 2.5
,但事实并非如此。根据this article ,0.1
无法使用IEEE 754准确表示,实际上表示为0.100000000000000005551...
。
在本例中,由于偏移量很小,商略高,这导致 n
的值为 3
,如下所示2
和 3
之间不再等距。
计算结果如下:
0.1 - 0.04 * 3 = 0.1 - 0.12 = -0.02 ~= -0.019999999999999997
关于Java Math.IEEERemainder 令人困惑的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919613/