2

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?

xnx
  • 24,509
  • 11
  • 70
  • 109
  • 1
    This question is not python-specific. – tmyklebu Jan 02 '15 at 18:10
  • Well, there's this: http://stackoverflow.com/questions/24442725/is-floating-point-addition-commutative-in-c which suggests that floating point addition is not commutative in C. But the answer below suggests that it _is_ in Python. – xnx Jan 02 '15 at 19:54

1 Answers1

2

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).

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281