Java Math.IEEERemainder 令人困惑的结果
Java Math.IEEERemainder confusing result
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
会 return 恰好 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 函数状态:
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
会 return 恰好 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