0

I am working on some floating point addition in Python, i found this difference, changing the order of addition changes the value.

v1=2.7776548790102065
v2=2.932026860135167
v3=-2.5635999386901154
v4=-5.884153623433478
v5=0.16152830205880864
v6=2.614447767673556
v7=5.651999753771971
v8=-7.074990233473147
v9=12.624973219138516

print(v1+v2+v3+v4+v5+v6+v7+v8+v9)  # 11.239886986191486  
print(v1+v4+v7+v2+v5+v8+v3+v6+v9)  # 11.239886986191484

can anyhow suggest me how to rectify this?

  • 1
    For reason checkout [Why does changing the sum order returns a different result?](https://stackoverflow.com/questions/19820297/why-does-changing-the-sum-order-returns-a-different-result) – DarrylG Dec 23 '20 at 12:25
  • You're missing v1 in your post. – DarrylG Dec 23 '20 at 12:27
  • Short answer: don't trust the last decimals. If your values are exact values and not approximations, you could have a look at the [decimal module](https://docs.python.org/3/library/decimal.html). – Thierry Lathuille Dec 23 '20 at 12:32
  • 1
    This issue is addressed in the Python docs [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html). which also explains you can use `math.fsum([v1, v2, v3, v4, v5, v6, v7, v8, v9])` which rearranges the order to get the sum with the smallest rounding error. – DarrylG Dec 23 '20 at 12:35
  • @DarrylG: It's not really rearranging; it tracks multiple partial intermediate sums (the example in your link couldn't benefit from rearranging; all the inputs are the same). But yes, `fsum` in either order of inputs produces the same output as the OP's second ordering of manual additions. – ShadowRanger Dec 23 '20 at 13:27

0 Answers0