Python floating point arithemetic basics

一世执手 提交于 2020-01-04 13:35:34

问题


As expected because of its finite precision, Python's floating point multiplication is not distributive over addition:

In [10]: 200 * 0.1 + 200 * 0.2
Out[10]: 60.0

In [11]: 200 * (0.1 + 0.2)
Out[11]: 60.00000000000001

And addition is not associative:

In [12]: 1e14 + (48.18 + 18.26)
Out[12]: 100000000000066.44

In [13]: (1e14 + 48.18) + 18.26
Out[13]: 100000000000066.45

But is addition commutative? multiplication?


回答1:


Yes, addition and multiplication are commutative (with the exception of when the result is NaN, but that's because NaN != NaN. In that case addition and multiplication produce the same result, it's just that this result is not equal to itself).

Both addition and multiplication of finite floating-point values are defined as the floating-point value nearest to the mathematical result of the respective operation. That is, respectively, rn(a + b) and rn(a * b).

These definitions are commutative because a + b = rn(a + b) = rn (b + a) = b + a (and similarly for multiplication).



来源:https://stackoverflow.com/questions/27743900/python-floating-point-arithemetic-basics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!