2

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.

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.