且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加和减去双打会产生奇怪的结果

更新时间:2023-01-07 13:47:32

在Java中, double 值为 IEEE浮点数。除非它们是2的幂(或2的幂的总和,例如1/8 + 1/4 = 3/8),否则即使它们具有高精度,也不能精确地表示它们。某些浮点运算会使这些浮点数中出现的舍入误差复杂化。在上面描述的情况下,浮点错误已经变得非常重要,足以显示在输出中。

In Java, double values are IEEE floating point numbers. Unless they are a power of 2 (or sums of powers of 2, e.g. 1/8 + 1/4 = 3/8), they cannot be represented exactly, even if they have high precision. Some floating point operations will compound the round-off error present in these floating point numbers. In cases you've described above, the floating-point errors have become significant enough to show up in the output.

数字的来源无关紧要是,它是从 JTextField 解析字符串还是指定 double 字面值 - 问题是在浮动中继承 - 点数表示。

It doesn't matter what the source of the number is, whether it's parsing a string from a JTextField or specifying a double literal -- the problem is inherit in floating-point representation.

解决方法:


  • 如果你认识你的话ll只有这么多的小数点,然后使用整数
    算术,然后转换为小数:

  • If you know you'll only have so many decimal points, then use integer arithmetic, then convert to a decimal:

(double) (51 + 1) / 10
(double) (48 - 4) / 10


  • 使用 BigDecimal

    如果必须使用 double ,则可以使用: //en.wikipedia.org/wiki/Kahan_summation_algorithm\">Kahan求和算法

    If you must use double, you can cut down on floating-point errors with the Kahan Summation Algorithm.