Why does python break IEEE 754 for 1.0/0.0 and 0.0/0.0?

Tim Peters tim.peters at gmail.com
Thu Jul 14 15:14:26 EDT 2005


[Grant Edwards]
> I've read over and over that Python leaves floating point
> issues up to the underlying platform.
>
> This seems to be largely true, but not always.  My underlying
> platform (IA32 Linux) correctly handles 1.0/0.0 and 0.0/0.0
> according to the IEEE 754 standard, but Python goes out of its
> way to do the wrong thing.

Python does go out of its way to raise ZeroDivisionError when dividing by 0.

> 1/0 is defined by the standard as +Inf and 0/0 is NaN.
>
> That's what my platform does for programs written in C.

IOW, that's what your platform C does (the behavior of these cases is
left undefined by the C89 standard, so it's not the case that you can
write a _portable_ C89 program relying on these outcomes).  What does
your platform C return for the integer expression 42/0?  Is any other
outcome "wrong"?

> Python apparently checks for division by zero and throws and exception
> rather than returning the correct value calculated by the
> underlying platform.
>
> Is there any way to get Python to return the correct results
> for those operations rather than raising an exception?

No, except when using the decimal module.  The latter provides all the
facilities in IBM's proposed standard for decimal floating-point,
which intends to be a superset of IEEE 854:

    http://www2.hursley.ibm.com/decimal/

It's relatively easy to do this in the decimal module because it
emulates, in software, all the gimmicks that most modern FPUs provide
in hardware.

Note that support for 754 was rare on Python platforms at the time
Python was designed, and nobody mentioned 754 support as even a vague
desire in those days.  In the absence of user interest, and in the
absence of HW support for NaNs or infinities on most Python platforms,
the decision to raise an exception was quite sensible at the time. 
Python could not have implemented 754 semantics without doing
emulating fp arithmetic in SW on most platforms (as the decimal module
does today), and for much the same reasons you can't give a non-silly
answer to my earlier "what does your platform C return for the integer
expression 42/0?" question today <wink>.

> There's no way to "resume" from the exception and return a
> value from an exception handler, right?

Correct.

Note that there's a huge, current, informed discussion of these issues
already in the math.nroot thread.



More information about the Python-list mailing list