Calculating the mean of a list of numbers (2016)
To see why, lets write our own mean:
This seems reasonable enough – it’s just the definition of the mean – but it’s wrong:
The problem is that finite floating point numbers may be large enough that their sum overflows to infinity. So to prevent that overflow, lets try to bound the size of our numbers by the length first:
In this case the problem you run into is not overflow, but the lack of precision of floating point numbers: Floating point numbers are only exact up to powers of two times an integer, so dividing by three will cause rounding errors. However getting an actually correct implementation of the mean (which would pass this test) is quite hard:
To see just how hard, here’s a 30 page paper on calculating the mean of two numbers.
Source: hypothesis.works