我如何在python中表示一个无限的数字?无论你在程序中输入哪个数字,都不应该大于这个表示无穷大的数字。
在Python中,你可以这样做:
test = float("inf")
在Python 3.5中,你可以:
import math
test = math.inf
然后:
test > 1
test > 10000
test > x
永远是真的。当然,如前所述,除非x也是无穷大或“nan”(“不是一个数字”)。
此外(Python 2。x ONLY),与Ellipsis相比,float(inf)较小,例如:
float('inf') < Ellipsis
返回true。
另一种不太方便的方法是使用Decimal class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
在python2。x有一个肮脏的黑客达到了这个目的(千万不要使用它,除非绝对必要):
None < any integer < any string
因此,检查i < "对于任何整数i都为真。
它在python3中已被合理地弃用。现在这样的比较以
TypeError: unorderable types: str() < int()
如果你使用SymPy,你也可以使用symphony .oo
>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan
etc.
用python表示∞
float("inf")或float("inf")或float("inf")或float("inf")或float("infinity")创建一个持有∞的float对象
你也可以在python中表示-∞
float("-inf")或float("-inf")或float("-inf")或float("-infinity")创建一个持有-∞的float对象
可以执行算术运算:
infinity = float("inf")
ninfinity = float("-inf")
nan = float("nan")
print(infinity*infinity)#inf
print(ninfinity+infinity)#not a number
print(1/-infinity)#is -0.0
print(nan*nan)# is not a number
print(1/infinity) # is 0.0 since 1/∞ is 0
输出:
$ python3 floating.py
inf
nan
-0.0
nan
0.0
总的来说,无穷有两种定义。
对于正无穷
posVal1 = math.inf
posVal2 = float("inf")
对于负无穷
negVal1 = -math.inf
negVal2 = float("-inf")
∞
1. 使用float('inf')和float('-inf)
positive_infinity = float('inf')
negative_infinity = float('-inf')
2. 使用Python的数学模块
import math
positive_infinity = math.inf
negative_infinity = -math.inf
3.整数的最大尺寸
import sys
maxSize = sys.maxsize # 9223372036854775807
minSize = -sys.maxsize # -9223372036854775807
4. 使用Python的十进制模块
from decimal import Decimal
positive_infinity = Decimal('Infinity')
negative_infinity = Decimal('-Infinity')