tags:

views:

73

answers:

3

Is there a way to make Python floating point numbers follow numpy's rules regarding +/- Inf and NaN? For instance, making 1.0/0.0 = Inf.

>>> from numpy import *
>>> ones(1)/0
array([ Inf])
>>> 1.0/0.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division

Numpy's divide function divide(1.0,0.0)=Inf however it is not clear if it can be used similar to from __future__ import division.

+1  A: 

I tried to do something similar, and I never figured out how to do it nicely. But, I can tell you a few things I tried, that didn't work:

  1. Setting float = numpy.float -- python still uses the old float
  2. trying to change float.div to a user-defined function -- "TypeError: can't set attributes of built-in/extension type float". Also, python doesn't like you mucking with the dict object in built-in objects.

I decided to go in and change the actual cpython source code to have it do what I wanted, which is obviously not practical, but it worked.

I think the reason why something like this is not possible is that float/int/list are implemented in C in the background, and their behavior cannot be changed cleanly from inside the language.

orangeoctopus
A: 

You could wrap all your floats in numpy.float64, which is the numpy float type.

a = float64(1.)
a/0 # Inf

In fact, you only need to wrap the floats on the left of arithmetic operations, obviously.

Olivier
I'm trying to provide numpy like floating point arithmetic in a REPL shell, so explicit wrapping isn't an option.
Tristan
+1  A: 

You should have a look at how Sage does it. IIRC they wrap the Python REPL in their own preprocessor.

dwf