Java Math.IEEERemainder 令人困惑的结果

标签 java math standards ieee-754

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 与整数 23 等距。难道我们不应该在这里选择n = 2,从而得到0.1 - 0.04*2 = 0.02,而不是-0.02吗?

最佳答案

参见:Is floating point math broken?

您可能认为 0.1/0.04 会准确返回 2.5,但事实并非如此。根据this article0.1无法使用IEEE 754准确表示,实际上表示为0.100000000000000005551...

在本例中,由于偏移量很小,商略高,这导致 n 的值为 3,如下所示23 之间不再等距。

计算结果如下:

0.1 - 0.04 * 3 = 0.1 - 0.12 = -0.02 ~= -0.019999999999999997

关于Java Math.IEEERemainder 令人困惑的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919613/

相关文章:

javascript - JavaScript <href> 链接的返回值应该如何处理?

sql - 数据库引擎和 ANSI SQL 合规性

java - 使用 Woodstox 解析 XML 时保持实体不变

java - 我不能在 Java 中使用数学方法

java - 找不到类 JsonObject

java - 如何仅使用两个变量找到两点之间的距离,然后存储所有点并获得形状?

java - 检索作业和/或进程

javascript - javascript 中的 Math.round MidPointRounding.AwayFromZero

c# - 如何警告由于类型转换导致的潜在算术错误?

javascript - 组合多个 jQuery 对话框选择器