Represent infinity as an integer in Python 2.7

瘦欲@ 提交于 2019-11-29 19:06:31

问题


I am wondering how to define inf and -inf as an int in Python 2.7. I tried and it seems inf and -inf only work as a float.

a = float('-inf') # works
b = float('inf') # works

c = int('-inf') # compile error, ValueError: invalid literal for int() with base 10: 'inf'
d = int('inf') # compile error, ValueError: invalid literal for int() with base 10: 'inf'

回答1:


To summarise what was said in the comments

There is no way to represent infinity as an integer in Python. This matches the behaviour of many other languages. However, due to Python's dynamic typing system, you can use float('inf') in place of an integer, and it will behave as you would expect.

As far as creating a 'double' for infinity, in Python there is just one floating point type, called float, unlike other languages such as Java which uses the term float and double for floating point numbers with different precision. In Python, floating point numbers usually use double-precision, so they act the same as doubles in Java.




回答2:


Something very big that is a integer (made in 3.x, not tested in 2.x):

0x40000 #will most likely crash the shell

so if you wanted a infinite variable you would do:

Infinity = 0x40000

You can do any Integer to Hexedecimal here:
https://www.binaryhexconverter.com/decimal-to-hex-converter
(make sure to add the 0x before the value it returns for python)



来源:https://stackoverflow.com/questions/40445920/represent-infinity-as-an-integer-in-python-2-7

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