Re: [SciPy-user] possible to get INF in divide by zero ?
![](https://secure.gravatar.com/avatar/c61cae23c7982ab69063f80425b0e09a.jpg?s=120&d=mm&r=g)
On jeudi 28 août 2008, Stef Mientki wrote:
I wonder if it's possible to get the MatLab behavior : divide by zero gives infinite (INF) ?
I even wonder if something like INF exists in python / scipy / numpy.
Isn't this already the behaviour of numpy ? In [6]: ones(10)/0 Warning: divide by zero encountered in divide Out[6]: array([ Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf]) Vincent -- Vincent Favre-Nicolin CEA Grenoble/INAC/SP2M http://inac.cea.fr Univ. Joseph Fourier (Grenoble) http://www.ujf-grenoble.fr ObjCryst & Fox http://objcryst.sf.net/Fox
![](https://secure.gravatar.com/avatar/0e31f673b2f054ea61da64e35bd52cc0.jpg?s=120&d=mm&r=g)
Vincent Favre-Nicolin wrote:
On jeudi 28 août 2008, Stef Mientki wrote:
I wonder if it's possible to get the MatLab behavior : divide by zero gives infinite (INF) ?
I even wonder if something like INF exists in python / scipy / numpy.
Isn't this already the behaviour of numpy ?
In [6]: ones(10)/0 Warning: divide by zero encountered in divide Out[6]: array([ Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf])
Vincent
Thanks, so it works for arrays, but not for normal integers:
3/0 Traceback (most recent call last): File "<interactive input>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
thanks, Stef Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629.
![](https://secure.gravatar.com/avatar/764323a14e554c97ab74177e0bce51d4.jpg?s=120&d=mm&r=g)
On Thu, Aug 28, 2008 at 02:48, Stef Mientki <s.mientki@ru.nl> wrote:
Thanks, so it works for arrays, but not for normal integers:
3/0 Traceback (most recent call last): File "<interactive input>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
Right. Python integers and floats explicitly check for this case and raise the error. numpy objects, either arrays or numpy scalar types, have a configurable mechanism. If you want scalars that work like this: In [1]: from numpy import * In [2]: float64(1.0) / 0.0 Out[2]: inf In [5]: seterr(divide='raise') Out[5]: {'divide': 'ignore', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'} In [6]: float64(1.0) / 0.0 --------------------------------------------------------------------------- FloatingPointError Traceback (most recent call last) /Users/rkern/Downloads/Video/avy/<ipython console> in <module>() FloatingPointError: divide by zero encountered in double_scalars In [7]: seterr(divide='warn') Out[7]: {'divide': 'raise', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'} In [8]: float64(1.0) / 0.0 /usr/local/bin/ipython:1: RuntimeWarning: divide by zero encountered in double_scalars #!/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python Out[8]: inf In [9]: seterr(divide='print') Out[9]: {'divide': 'warn', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'} In [10]: float64(1.0) / 0.0 Warning: divide by zero encountered in double_scalars Out[10]: inf In [12]: seterr(divide='ignore') Out[12]: {'divide': 'print', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'} In [13]: float64(1.0) / 0.0 Out[13]: inf In [14]: seterr? Type: function Base Class: <type 'function'> String Form: <function seterr at 0x18e8e30> Namespace: Interactive File: /Users/rkern/svn/numpy/numpy/core/numeric.py Definition: seterr(all=None, divide=None, over=None, under=None, invalid=None) Docstring: Set how floating-point errors are handled. Valid values for each type of error are the strings "ignore", "warn", "raise", and "call". Returns the old settings. If 'all' is specified, values that are not otherwise specified will be set to 'all', otherwise they will retain their old values. Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings. Example: >>> seterr(over='raise') # doctest: +SKIP {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> seterr(all='warn', over='raise') # doctest: +SKIP {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> int16(32000) * int16(3) # doctest: +SKIP Traceback (most recent call last): File "<stdin>", line 1, in ? FloatingPointError: overflow encountered in short_scalars >>> seterr(all='ignore') # doctest: +SKIP {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco
![](https://secure.gravatar.com/avatar/38d5ac232150013cbf1a4639538204c0.jpg?s=120&d=mm&r=g)
Robert Kern wrote:
On Thu, Aug 28, 2008 at 02:48, Stef Mientki <s.mientki@ru.nl> wrote:
Thanks, so it works for arrays, but not for normal integers:
3/0 Traceback (most recent call last): File "<interactive input>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
Right. Python integers and floats explicitly check for this case and raise the error. numpy objects, either arrays or numpy scalar types, have a configurable mechanism. If you want scalars that work like this:
In [1]: from numpy import *
In [2]: float64(1.0) / 0.0 Out[2]: inf
In [5]: seterr(divide='raise') Out[5]: {'divide': 'ignore', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'}
In [6]: float64(1.0) / 0.0 --------------------------------------------------------------------------- FloatingPointError Traceback (most recent call last)
/Users/rkern/Downloads/Video/avy/<ipython console> in <module>()
FloatingPointError: divide by zero encountered in double_scalars
In [7]: seterr(divide='warn') Out[7]: {'divide': 'raise', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'}
In [8]: float64(1.0) / 0.0 /usr/local/bin/ipython:1: RuntimeWarning: divide by zero encountered in double_scalars #!/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python Out[8]: inf
In [9]: seterr(divide='print') Out[9]: {'divide': 'warn', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'}
In [10]: float64(1.0) / 0.0 Warning: divide by zero encountered in double_scalars Out[10]: inf
In [12]: seterr(divide='ignore') Out[12]: {'divide': 'print', 'invalid': 'ignore', 'over': 'ignore', 'under': 'ignore'}
In [13]: float64(1.0) / 0.0 Out[13]: inf
In [14]: seterr? Type: function Base Class: <type 'function'> String Form: <function seterr at 0x18e8e30> Namespace: Interactive File: /Users/rkern/svn/numpy/numpy/core/numeric.py Definition: seterr(all=None, divide=None, over=None, under=None, invalid=None) Docstring: Set how floating-point errors are handled.
Valid values for each type of error are the strings "ignore", "warn", "raise", and "call". Returns the old settings. If 'all' is specified, values that are not otherwise specified will be set to 'all', otherwise they will retain their old values.
Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings.
Example:
>>> seterr(over='raise') # doctest: +SKIP {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
>>> seterr(all='warn', over='raise') # doctest: +SKIP {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
>>> int16(32000) * int16(3) # doctest: +SKIP Traceback (most recent call last): File "<stdin>", line 1, in ? FloatingPointError: overflow encountered in short_scalars >>> seterr(all='ignore') # doctest: +SKIP {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
In Python (probably system and version dependent) you can generate infinity as float('inf'). You are overlooking the basic definition of infinity (http://en.wikipedia.org/wiki/Infinity) and numerical representation of numbers in computer science especially integer versus floating point. In computer science integers refer to a finite range ( http://en.wikipedia.org/wiki/Integer_(computer_science) ) which is contrary to the meaning of infinity. Technically the same argument holds true for floating point number, but, fortunately there is the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754 see for example, http://en.wikipedia.org/wiki/IEEE_754) that NumPy supports. This standard allows for representations of 'special' floating point values (such as positive infinity, negative infinity and Not a Number) and, more importantly, operations involving these values. Using integers:
numpy.ones(10, dtype=numpy.int) array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) numpy.ones(10, dtype=numpy.int)/0 array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) type((numpy.ones(10, dtype=numpy.int)/0)[0]) <type 'numpy.int64'>
Compared to using floats (the default of dtype of numpy.ones, for example, http://sd-2116.dedibox.fr/pydocweb/doc/numpy.matlib.ones/ ):
numpy.ones(10, dtype=numpy.float)/0 array([ Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf]) type((numpy.ones(10, dtype=numpy.float)/0)[0]) <type 'numpy.float64'>
Bruce
![](https://secure.gravatar.com/avatar/0e31f673b2f054ea61da64e35bd52cc0.jpg?s=120&d=mm&r=g)
another observation:
a=numpy.array([2,3]) a/0 array([0, 0])
??? cheers, Stef Vincent Favre-Nicolin wrote:
On jeudi 28 août 2008, Stef Mientki wrote:
I wonder if it's possible to get the MatLab behavior : divide by zero gives infinite (INF) ?
I even wonder if something like INF exists in python / scipy / numpy.
Isn't this already the behaviour of numpy ?
In [6]: ones(10)/0 Warning: divide by zero encountered in divide Out[6]: array([ Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf, Inf])
Vincent
Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629.
![](https://secure.gravatar.com/avatar/da3a0a1942fbdc5ee9a9b8115ac5dae7.jpg?s=120&d=mm&r=g)
Thu, 28 Aug 2008 09:56:36 +0200, Stef Mientki wrote:
another observation:
a=numpy.array([2,3]) a/0 array([0, 0])
Division in Numpy preserves the data types: in this case you have an integer array divided by an integer, so the output is also an integer. But Inf is not one of integers so something must be substituted; and it is zero. There probably was some reason for this choice... If you change your seterr configuration frmo divide='ignore' you should get a warning, see http://mentat.za.net/numpy/refguide/routines.math.xhtml#numpy.divide -- Pauli Virtanen
![](https://secure.gravatar.com/avatar/07a8f7b8193f92fa9f33f6a07691c48a.jpg?s=120&d=mm&r=g)
thank you all for the explanations. I'm a practical engineer, who almost never divide by zero. But the question came from my son, familiar with python and a little with scipy. After his first lesson in MatLab, he said: Oh what a beautiful environment is MatLab, it's even capable to divide by zero without errors. So for the moment probably MatLab is better suited for educational purposes. I'll ask him again to compare scipy and Matlab, after a few weeks ;-) cheers, Stef Pauli Virtanen wrote:
Thu, 28 Aug 2008 09:56:36 +0200, Stef Mientki wrote:
another observation:
a=numpy.array([2,3]) a/0 array([0, 0])
Division in Numpy preserves the data types: in this case you have an integer array divided by an integer, so the output is also an integer.
But Inf is not one of integers so something must be substituted; and it is zero. There probably was some reason for this choice...
If you change your seterr configuration frmo divide='ignore' you should get a warning, see http://mentat.za.net/numpy/refguide/routines.math.xhtml#numpy.divide
![](https://secure.gravatar.com/avatar/6401b8425eed08fcbaffffeeaceac894.jpg?s=120&d=mm&r=g)
Stef Mientki wrote:
thank you all for the explanations.
I'm a practical engineer, who almost never divide by zero. But the question came from my son, familiar with python and a little with scipy. After his first lesson in MatLab, he said: Oh what a beautiful environment is MatLab, it's even capable to divide by zero without errors. So for the moment probably MatLab is better suited for educational purposes.
NO!!!
I'll ask him again to compare scipy and Matlab, after a few weeks ;-)
The fundamental difference here is that Matlab operates using double precision numbers for *everything* by default. I personally consider that a design flaw. Numpy is being smart and letting you use integers if that's what you give it. So this isn't some limitation of numpy, it's just a slight difference of "opinion" between the packages. Numpy is capable of the same behavior with just one of two minor tweaks to the example:
a = np.array([2., 3.]) #Note the decimal points, this makes floats a/0 array([ Inf, Inf])
-or-
a = np.array([2, 3], dtype=np.float32) #Explicitly ask for floats a/0 array([ Inf, Inf], dtype=float32)
Ryan -- Ryan May Graduate Research Assistant School of Meteorology University of Oklahoma
![](https://secure.gravatar.com/avatar/da3a0a1942fbdc5ee9a9b8115ac5dae7.jpg?s=120&d=mm&r=g)
Fri, 29 Aug 2008 12:23:33 +0000, Pauli Virtanen wrote:
Thu, 28 Aug 2008 09:56:36 +0200, Stef Mientki wrote:
another observation:
a=numpy.array([2,3]) a/0 array([0, 0])
Division in Numpy preserves the data types: in this case you have an integer array divided by an integer, so the output is also an integer.
But Inf is not one of integers so something must be substituted; and it is zero. There probably was some reason for this choice...
Matlab substitutes MAXINT here:
x = zeros([2,2],'int32') 1./x
ans = 2147483647 2147483647 2147483647 2147483647 I don't know the rationale behind the choice 0 in Numpy... -- Pauli Virtanen
participants (7)
-
Bruce Southey
-
Pauli Virtanen
-
Robert Kern
-
Ryan May
-
Stef Mientki
-
Stef Mientki
-
Vincent Favre-Nicolin