How do I type a floating point infinity literal in python

PythonFloating PointPortabilityNumerical

Python Problem Overview


How do I type a floating point infinity literal in python?

I have heard

 inf = float('inf')

is non portable. Thus, I have had the following recommended:

 inf = 1e400

Is either of these standard, or portable? What is best practice?

Python Solutions


Solution 1 - Python

In python 2.6 it is portable if the CPU supports it

> The float() function will now turn the > string nan into an IEEE 754 Not A > Number value, and +inf and -inf into > positive or negative infinity. This > works on any platform with IEEE 754 > semantics.

Solution 2 - Python

float('inf') is non portable as in not portable back to Python 2.5 when the string output varies between platforms. From 2.6 and onwards float('inf') is guaranteed to work on IEEE-754-compliance platforms (ref: http://www.python.org/dev/peps/pep-0754/).

(And the recommendation seems to be in the range 1e30000, not just 1e400.)

Solution 3 - Python

Perhaps you could do something like this

try:
    inf = float('inf')
except:  # check for a particular exception here?
    inf = 1e30000

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfmarkView Question on Stackoverflow
Solution 1 - PythonmmmmmmView Answer on Stackoverflow
Solution 2 - PythonkennytmView Answer on Stackoverflow
Solution 3 - PythonJohn La RooyView Answer on Stackoverflow