为什么我会以不同的顺序乘以三个double值而得到不同的答案? [英] Why do I get different answers multiplying three double values in a different order?

查看:102
本文介绍了为什么我会以不同的顺序乘以三个double值而得到不同的答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java执行以下代码,但是对于在数学上应该是相同的数字,我得到了两个不同的答案.

I am executing the following code in java but i got two different answers for what should be the same number mathematically.

public class TestClass {

    public static void main(String[] args) {

        double a=0.01;
        double b=4.5;
        double c=789;       
        System.out.println("Value1---->"+(a*b*c));
        System.out.println("Value2---->"+(b*c*a));      
    }
}

输出:

Value1---->35.504999999999995
Value2---->35.505

请告诉我为什么我得到这个结果.

Please tell me why I get this result.

推荐答案

浮点数具有一定的精度.某些分数不能用浮点数正确显示,这就是为什么会出现舍入错误的原因.

Floating point numbers have a certain precision. Some fractions can not be displayed correctly with floating point numbers, that's why rounding errors can occur.

由于计算的优先级,结果有所不同.您的每个计算都包含两个乘法. Java中的乘法*运算符具有从左到右的关联性.这意味着在(a*b*c)中,首先计算a*b,然后像在((a*b)*c)中一样乘以c.这些计算链之一恰好会产生舍入误差,因为其中的数字根本无法表示为浮点数.

The results are different because of the precedence of the calculations. Each of your calculations consists of two multiplications. The multiply * operator in Java has a left to right associativity. That means that in (a*b*c), a*b is calculated first and the multiplied by c as in ((a*b)*c). One of those calculation chains happens to produce a rounding error because a number in it simply can't be represented as a floating point number.

这篇关于为什么我会以不同的顺序乘以三个double值而得到不同的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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