79

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?

fmark
  • 57,259
  • 27
  • 100
  • 107

4 Answers4

62

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.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
  • 16
    @fmark: Good luck finding a platform that Python runs on but that doesn't have IEEE 754 semantics. In theory, `float('inf')` should raise `ValueError` on these platforms, but to my knowledge this behaviour has never been tested, because Python (well, recent versions of Python, at least) has yet to meet such a platform. In practice don't worry about it. – Mark Dickinson May 27 '10 at 10:09
16

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.)

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
12

Perhaps you could do something like this

try:
    inf = float('inf')
except:  # check for a particular exception here?
    inf = 1e30000
vaultah
  • 44,105
  • 12
  • 114
  • 143
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 6
    +1. `float('inf')` is definitely to be preferred, in general. It's even possible that 'inf = 1e30000` might start raising `OverflowError` instead of producing an infinity in some future version of Python. – Mark Dickinson May 27 '10 at 10:06
2

Starting from Python 3.6, you can use math.inf.

import math
math.inf
barjak
  • 10,842
  • 3
  • 33
  • 47