Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I type a floating point infinity literal in python

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?

like image 531
fmark Avatar asked May 27 '10 09:05

fmark


People also ask

What is float ('- INF ') in Python?

But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float('inf') as an integer to represent it as infinity.

How do you type infinity symbol in Python?

In Python, there is no way or method to represent infinity as an integer. This matches the fundamental characteristic of many other popular programming languages. But due to python being dynamically typed language, you can use float(inf) as an integer to represent it as infinity.

How do you represent a floating-point in Python?

The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers.


2 Answers

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.

like image 129
mmmmmm Avatar answered Sep 17 '22 14:09

mmmmmm


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

like image 41
kennytm Avatar answered Sep 19 '22 14:09

kennytm