How do I type a floating point infinity literal in python

与世无争的帅哥 提交于 2019-12-17 18:00:25

问题


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?


回答1:


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.




回答2:


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




回答3:


Perhaps you could do something like this

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


来源:https://stackoverflow.com/questions/2919754/how-do-i-type-a-floating-point-infinity-literal-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!