ssi*_*ral 511 python infinite infinity
如何在python中表示无限数?无论您在程序中输入哪个数字,任何数字都不应大于此无穷大的表示.
Wil*_*all 633
在Python中,您可以:
test = float("inf")
Run Code Online (Sandbox Code Playgroud)
在Python 3.5中,您可以:
import math
test = math.inf
Run Code Online (Sandbox Code Playgroud)
然后:
test > 1
test > 10000
test > x
Run Code Online (Sandbox Code Playgroud)
永远都是真的.当然,除非指出,x也是无穷大或"nan"("不是数字").
另外(Python 2.x ONLY),与之比较Ellipsis,float(inf)较小,例如:
float('inf') < Ellipsis
Run Code Online (Sandbox Code Playgroud)
会回归真实.
rig*_*old 66
从Python 3.5开始,您可以使用math.inf:
>>> import math
>>> math.inf
inf
Run Code Online (Sandbox Code Playgroud)
Sна*_*ƒаӽ 31
似乎没有人明确提到负无穷大,所以我想我应该加上它.
对于正无穷大(仅为了完整性):
math.inf
Run Code Online (Sandbox Code Playgroud)
对于负无穷大:
-math.inf
Run Code Online (Sandbox Code Playgroud)
Den*_*sky 24
另一种不太方便的方法是使用Decimal类:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
Run Code Online (Sandbox Code Playgroud)
Len*_*oyt 22
NumPy库中有一个无穷大:from numpy import inf.为了获得负无穷大,可以简单地写-inf.
Eri*_*nga 15
1. 使用float(\'inf\')和float(\'-inf)
positive_infinity = float(\'inf\') \nnegative_infinity = float(\'-inf\')\nRun Code Online (Sandbox Code Playgroud)\n2.使用Python\xe2\x80\x99s数学模块
\nimport math\n \npositive_infinity = math.inf \nnegative_infinity = -math.inf \nRun Code Online (Sandbox Code Playgroud)\n3. 整数maxsize
import sys\n\nmaxSize = sys.maxsize \nminSize = -sys.maxsize \nRun Code Online (Sandbox Code Playgroud)\n4.使用Python\xe2\x80\x99s十进制模块
\nfrom decimal import Decimal\n \npositive_infinity = Decimal(\'Infinity\') \nnegative_infinity = Decimal(\'-Infinity\') \nRun Code Online (Sandbox Code Playgroud)\n5.使用Numpy库
\nfrom numpy import inf\n\npositive_infinity = inf \nnegative_infinity = -inf \nRun Code Online (Sandbox Code Playgroud)\n
Ant*_*ins 12
在python2.x中有一个脏的hack用于此目的(除非绝对必要,否则不要使用它):
None < any integer < any string
Run Code Online (Sandbox Code Playgroud)
因此,检查i < ''适用True于任何整数i.
它在python3中被合理地弃用了.现在这样的比较结束了
TypeError: unorderable types: str() < int()
Run Code Online (Sandbox Code Playgroud)
此外,如果您使用 SymPy,则可以使用 sympy.oo
>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan
Run Code Online (Sandbox Code Playgroud)
等等。
| 归档时间: |
|
| 查看次数: |
532659 次 |
| 最近记录: |