Why does changing the sum order returns a different result?

后端 未结 6 1387
别那么骄傲
别那么骄傲 2020-11-30 16:18

Why does changing the sum order returns a different result?

23.53 + 5.88 + 17.64 = 47.05

23.53 + 17.64 + 5.8

6条回答
  •  半阙折子戏
    2020-11-30 17:13

    Jon's answer is of course correct. In your case the error is no larger than the error you would accumulate doing any simple floating point operation. You've got a scenario where in one case you get zero error and in another you get a tiny error; that's not actually that interesting a scenario. A good question is: are there scenarios where changing the order of calculations goes from a tiny error to a (relatively) enormous error? The answer is unambiguously yes.

    Consider for example:

    x1 = (a - b) + (c - d) + (e - f) + (g - h);
    

    vs

    x2 = (a + c + e + g) - (b + d + f + h);
    

    vs

    x3 = a - b + c - d + e - f + g - h;
    

    Obviously in exact arithmetic they would be the same. It is entertaining to try to find values for a, b, c, d, e, f, g, h such that the values of x1 and x2 and x3 differ by a large quantity. See if you can do so!

提交回复
热议问题