以不同顺序添加相同的双打时的结果不同 [英] Different results when adding same doubles in different order

查看:68
本文介绍了以不同顺序添加相同的双打时的结果不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么加相同的数字时输出会不同?

Why is the output different when adding same numbers?

public class Test {

    public static void main(String a[]) {

        double[] x = new double[]{3.9, 4.3, 3.6, 1.3, 2.6};
        System.out.println(">>>>>>> " + sum(x));
    }

    public static double sum(double[] d) {

        double sum = 0;
        for (int i = 0; i < d.length; i++) {
            sum += d[i];
        }
        return sum;
    }
}

输出为: 15.7

如果我交换值

double[] x = new double[] {2.6, 3.9, 4.3, 3.6, 1.3};

我得到的输出为: 15.700000000000001

我如何获得相同的输出?

推荐答案

浮点数丢失精度进行更多操作.通常,首先添加最小的数字即可获得最高的精度.(因此,结果确实取决于操作顺序)

Floating point numbers lose precision as you do more operations. Generally, you get the highest precision by adding the smallest numbers first. (So the result does depend on the order of operations)

除了保持相同的操作顺序外,您还必须使用 strictfp 在不同的平台上获得相同的结果.

In addition to maintaining the same order of operations, you'll also have to use strictfp to get the same result on different platforms.

或者更好的是,不要使用浮点数:使用

Or better yet, don't use floating points: use a BigDecimal instead.

这篇关于以不同顺序添加相同的双打时的结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆