> sum(x)/n is much faster than using pythons built in mean function.
`statistics.mean` uses `_sum` which tries to avoid some basic round-off errors[1]. I think the implementation of `_sum` is needlessly baroque because the implementors are trying to handle multiple types in the same code in a not so type-aware language. Regardless, using `statistics.mean` instead of `sum(x)/len(x)` would eliminate the most common rounding error source.
As for statistical modelling handled by directly inverting matrices, there the problem is singular matrices that appear to be non-singular due to the vagaries of floating point arithmentic in addition to failing to use stable numeric techniques.
The point remains. The detriment to science are people who convert textbook formulas directly to code instead of being aware of implementation with good numerical properties.
Note:
>>> x = [1e9 + .1, 1.1] * 50000
>>> sum(x)/len(x)
500000000.60091573
whereas
>>> import statistics
>>> statistics.mean(x)
500000000.6
See also my blog post "How you average numbers matters"[2].
> Now, in the real world, you have programs that ingest untold amounts of data. They sum numbers, divide them, multiply them, do unspeakable things to them in the name of “big data”. Very few of the people who consider themselves C++ wizards, or F# philosophers, or C# ninjas actually know that one needs to pay attention to how you torture the data. Otherwise, by the time you add, divide, multiply, subtract, and raise to the nth power you might be reporting mush and not data.
> One saving grace of the real world is the fact that a given variable is unlikely to contain values with such an extreme range. On the other hand, in the real world, one hardly ever works with just a single variable, and one can hardly every verify the results of individual summations independently.
Correct algorithms may be slower, but I am hoping that it is easy understand why they ought to be preferred.
[1]: https://github.com/python/cpython/blob/5571cabf1b3385087aba2...
[2]: https://www.nu42.com/2015/03/how-you-average-numbers.html