Question

I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used float("inf"), and now I find it is unavailable on Python 2.5. Is there a backport of it?

Was it helpful?

Solution 4

I created a backport, tested on Python 2.5+, can probably be easily made to work on Python 2.4:

https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/infinity.py

OTHER TIPS

Spelling it either the long way or the short way works fine for me:

$ python2.4 -c "print float('inf')+200"
inf
$ python2.5 -c "print float('inf')+200"
inf
$ python2.5 -c "print float('infinity')+200"
inf
$ python2.4 -c "print float('infinity')+200"
inf

The -c flag means "execute the following arguments as a Python command."

PEP754 (which was rejected) does mention your issue about special IEEE-754 values. It suggests using something like 1e300000 to generate a floating point overflow and create inf, but it does note that this is ugly and not guaranteed to be portable.

You should be able to fake it up by giving Python a sufficiently large floating point constant instead. For instance:

>>> 1e100000
inf
>>> float('inf') == 1e1000000
True
>>> float('inf') == 2e1000000
True

The decimal module is available since Python 2.4 and supports positive or negative infinite decimals. It does not always behave like a float (eg. adding a decimal and a float is not supported) but does the right thing for comparison, which was good enough for me.

>>> decimal.Decimal('Infinity') > 1e300
True

Borrowing NumPy for a few lines:

import numpy as np

inf = float(np.inf)

Here, inf is a regular python float, so you don't need to bother with NumPy any further.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top