Turn off ZeroDivisionError?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Feb 11 07:07:49 EST 2008


On Sun, 10 Feb 2008 23:34:51 +0100, Christian Heimes wrote:

> Grant Edwards wrote:
>> You must have gone to a different school than I did.  I learned that
>> for IEEE floating point operations a/0. is INF with the same sign as a
>> (except when a==0, then you get a NaN).
> 
> I'm not talking about CS and IEEE floating point ops. I was referring to
> plain good old math. Python targets both newbies and professionals.
> That's the reason for two math modules (math and cmath).

Alas, Python doesn't do "plain good old math" either:

>>> 1/3 + 1/3 + 1/3  # three thirds makes one exactly
0

Hmmm... okay, let's try this:

>>> import math
>>> math.sqrt(10)**2 == 10
False

How about something a little more advanced? Euler's Identity says that e 
to the power of i*pi equals -1. Python writes i as j, so we write this:

>>> math.e**(math.pi*1j) == -1
False

How about something absolutely fundamental to good old maths, like the 
Distributive Law?

>>> 0.3*(0.1 + 0.9) == (0.3*0.1) + (0.3*0.9)  # a(b+c) = ab + ac
False

Or even something as basic as this:

>>> 0.1 + 0.9 - 0.9 == 0.1  # x + y - y = x
False


Floating point maths is not and can not be the same as the maths we learn 
about in schools. Floats are not reals. We should just give up the 
fantasy of making floats the same as real numbers, because it cannot 
happen. I applaud the effort to hide the complexity of floating point 
maths, but compared to the things newbies already get surprised by, 
having 1.0/0 return inf isn't even a blip on the radar.

In fact, most school kids learn that "one over nothing is infinity" (not 
from their teachers, I think they pick it up by osmosis), so that will 
probably cause less grief than the other examples I gave.



[...]

> Python's a/0 outcome doesn't violate the standards because Python
> doesn't promise to follow the IEEE 754 standard in the first place. Mark
> and I are working hard to make math in Python more reliable across
> platforms. So far we have fixed a lot of problems but we haven't
> discussed the a/0 matter.

And thank you for your efforts, they are appreciated.


> The best we could give you is an option that makes Python's floats more
> IEEE 754 like:
> 
>>>> from somemodule import ieee754
>>>> with ieee754:
> ...    r = a/0
> ...    print r
> inf


Sounds like a good plan to me. I could live with that.



-- 
Steven



More information about the Python-list mailing list