On Thu, Dec 26, 2019 at 05:51:09PM -0000, Marco Sulla via Python-ideas wrote:
> Stephen J. Turnbull wrote:
> > > from statistics import mean
> > > sum([1e16,1,1])/3 == 1e16/3 # surprise!
> > > True
> > > mean([1e16,1,1]) == 1e16/3
> > > False
> > > Regards,
>
> Python 3.9.0a0 (heads/master-dirty:d8ca2354ed, Oct 30 2019, 20:25:01)
> [GCC 9.2.1 20190909] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> sum([1e16,1,1])/3
> 3333333333333333.5
I'm not sure what point your example is meant to show, beyond what
Stephen already showed. But for the record, the mathematically exact
answer is 3333333333333334 so the naive version with sum is not too far
off in this example.
There are other examples where the naive version is much worse:
py> sum([3, 1e16, -1e16])/3 # Naive version.
1.3333333333333333
py> statistics.mean([3, 1e16, -1e16]) # Correct answer.
1.0
py> sum([1, 1e16, -1e16])/3 # Naive version.
0.0
py> statistics.mean([1, 1e16, -1e16]) # Correct answer.
0.3333333333333333
The above examples are contrived, but in general the naive version is
subject to rounding error, which can be significant even for more
realistic data.
If you don't care about support for Decimal and Fraction, but do care
about speed, the fmean function in 3.8 is much faster while still
being significantly more accurate than the naive version.
py> statistics.fmean([3, 1e16, -1e16])
1.0
py> statistics.fmean([1, 1e16, -1e16])
0.3333333333333333
To my mind, the mean() function's biggest advantage is that you can
force an exact result with no rounding by using Fractions:
py> statistics.mean([Fraction(1), 5, 2])
Fraction(8, 3)
py> statistics.fmean([Fraction(1), 5, 2])
2.6666666666666665
but the cost of that is that mean() is significantly slower.
--
Steven
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/BNCLMYVPNCT5YMAH4NTZJZ7OW3UIZU62/
Code of Conduct: http://python.org/psf/codeofconduct/