问题
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