HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python versus Matlab on the quantity 1/0

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
thematlabversusquantitypython

Problem

Python and Matlab seem to disagree on the division by 0.

Python:

>>> 1 / 0
Traceback (most recent call last):
File "", line 1, in 
ZeroDivisionError: division by zero


Matlab:

>>> 1 / 0
Inf


with the usual properties of $\infty$ for Inf.

Which one is correct when it comes to the IEEE double-precision format?

Solution

In the copy that I have of IEEE 754 (2008) it says

7.3 Division by zero 7.3.0

The divideByZero exception shall be signaled if and only if an exact infinite result is defined for an operation on finite operands. The default result of divideByZero shall be an ∞ correctly signed according to the operation:

― For division, when the divisor is zero and the dividend is a finite non-zero number, the sign of the infinity is the exclusive OR of the operands’ signs (see 6.3).

― For logB(0) when logBFormat is a floating-point format, the sign of the infinity is minus (−∞).

Python is choosing that the exception that the standard requires is a Python exception. My own interpretation is that this agrees with section 7.3. We don't get the value float('inf') because the exception interrupts the execution. I personally find it a bit inconvenient. I don't know the reasons they had for this choice.

One can get the behavior of obtaining a value by using numpy. With

x = numpy.float64(1.0)/numpy.float64(0.0)


we get

x = numpy.float64('inf')


and a RuntimeWarning. Alternatively, one can capture the exception ZeroDivisionError and produce the result float('inf') ourselves.

In Matlab we get inf as the result. It agrees with the standard because I think there is a warning (a flag) that can be seen by setting warning on MATLAB:divideByZero.

Code Snippets

x = numpy.float64(1.0)/numpy.float64(0.0)
x = numpy.float64('inf')

Context

StackExchange Computer Science Q#138997, answer score: 3

Revisions (0)

No revisions yet.