Why does changing the sum order returns a different result?

后端 未结 6 1398
别那么骄傲
别那么骄傲 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:06

    This actually covers much more than just Java and Javascript, and would likely affect any programming language using floats or doubles.

    In memory, floating points use a special format along the lines of IEEE 754 (the converter provides much better explanation than I can).

    Anyways, here's the float converter.

    http://www.h-schmidt.net/FloatConverter/

    The thing about the order of operations is the "fineness" of the operation.

    Your first line yields 29.41 from the first two values, which gives us 2^4 as the exponent.

    Your second line yields 41.17 which gives us 2^5 as the exponent.

    We're losing a significant figure by increasing the exponent, which is likely to change the outcome.

    Try ticking the last bit on the far right on and off for 41.17 and you can see that something as "insignificant" as 1/2^23 of the exponent would be enough to cause this floating point difference.

    Edit: For those of you who remember significant figures, this would fall under that category. 10^4 + 4999 with a significant figure of 1 is going to be 10^4. In this case, the significant figure is much smaller, but we can see the results with the .00000000004 attached to it.

提交回复
热议问题