Python fails on math

Benjamin Kaplan benjamin.kaplan at case.edu
Tue Feb 22 14:37:44 CET 2011


On Tue, Feb 22, 2011 at 8:20 AM, christian schulze
<xcr4cx at googlemail.com> wrote:
> Hey guys,
>
> I just found out, how much Python fails on simple math. I checked a
> simple equation for a friend.
>
> [code]
>>>> from math import e as e
>>>> from math import sqrt as sqrt
>>>> 2*e*sqrt(3) - 2*e == 2*e*(sqrt(3) - 1)
> False
> [/code]
>
> So WTF? The equation is definitive equivalent. (See http://mathbin.net/59158)
>
> PS:
>
> #1:
>>>> 2.0 * e * sqrt(3.0) - 2.0 * e
> 3.9798408154464964
>
> #2:
>>>> 2.0 * e * (sqrt(3.0) -1.0)
> 3.979840815446496
>
> I was wondering what exactly is failing here. The math module? Python,
> or the IEEE specifications?
>

1 / 3 = 0.33333333333
1 / 3 * 3 = 0.333333333 * 3 =  0.999999999  != 1
OMG MATH IS BROKEN!!!!!!!!!!!!!!!

Unless you're doing symbolic manipulation or have infinite precision,
it's impossible to accurately represent most values. In fact, e is not
really e, it's just the closest approximation to e we can get using 64
bits. So the exact amount it's off is a result of IEEE. The fact that
it's off at all is a result of us not having infinite memory.



More information about the Python-list mailing list