Someone just asked why sum(myfloats)
differed from sum(reversed(myfloats))
. Quickly got duped to Is floating point math broken? and deleted.
But it made me curious: How many different sums can we get from very few floats, just by summing them in different orders? With three floats, we can get three different sums:
>>> from itertools import permutations
>>> for perm in permutations([0.2, 0.3, 0.4]):
print(perm, sum(perm))
(0.2, 0.3, 0.4) 0.9
(0.2, 0.4, 0.3) 0.9000000000000001
(0.3, 0.2, 0.4) 0.9
(0.3, 0.4, 0.2) 0.8999999999999999
(0.4, 0.2, 0.3) 0.9000000000000001
(0.4, 0.3, 0.2) 0.8999999999999999
I believe addition is commutative (i.e., a + b == b + a
) for floats. And we have three choices for the first pair to add and then one "choice" for the second add, so three sums is the most we can get with just three values.
Can we get more than three different sums with four values? With some experiments I didn't find such a case. If we can't: why not? If we can: how many? How many with five?
As Eric just pointed out, for more than three values there are also different possibilities than just summing left to right, for example (a+b) + (c+d)
. I'm interested in any way to add the numbers.
Note I'm talking about 64-bit floats (I'm a Python guy, I know in other languages they're often called doubles).