如何在Python中表示无限数?

问题描述 投票:0回答:13

如何在Python中表示无限数?无论您在程序中输入哪个数字,任何数字都不应大于这个无穷大的表示形式。

python infinite infinity
13个回答
939
投票

在Python中,你可以这样做:

test = float("inf")

在Python 3.5中,你可以这样做:

import math
test = math.inf

然后:

test > 1
test > 10000
test > x

永远都是真的。当然,除非如所指出的那样,x 也是无穷大或“nan”(“不是数字”)。

此外(仅限 Python 2.x),与

Ellipsis
相比,
float(inf)
较小,例如:

float('inf') < Ellipsis

将返回true。


113
投票

从Python 3.5开始你可以使用

math.inf
:

>>> import math
>>> math.inf
inf

103
投票

似乎没有人明确提到负无穷大,所以我想我应该添加它。

对于负无穷大:

-math.inf

对于正无穷大(只是为了完整性):

math.inf

34
投票

我不知道你到底在做什么,但是

float("inf")
给你一个浮点无穷大,它比任何其他数字都大。


33
投票

NumPy 库中有无穷大:

from numpy import inf
。要获得负无穷大,只需写
-inf


27
投票

另一种不太方便的方法是使用

Decimal
类:

from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')

16
投票

在 python2.x 中,有一个肮脏的 hack 可以达到此目的(除非绝对必要,否则不要使用它):

None < any integer < any string

因此,对于任何整数

i < ''
,检查
True
都保持
i

它在 python3 中已被合理弃用。现在这样的比较最终是

TypeError: unorderable types: str() < int()

13
投票

无限

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.整数

maxsize

import sys

maxSize = sys.maxsize 
minSize = -sys.maxsize 

4。使用Python的decimal模块

from decimal import Decimal
 
positive_infinity = Decimal('Infinity') 
negative_infinity = Decimal('-Infinity') 

5。使用 Numpy 库

from numpy import inf

positive_infinity = inf 
negative_infinity = -inf 

12
投票

如果您使用 SymPy,您也可以使用

sympy.oo

>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan

等等


2
投票

对于正无穷

pos_inf_val = float("infinity")

对于负无穷

neg_inf_val = float("-infinity")

0
投票

代表python

中的

float("inf")
float("INF")
float("Inf")
float("inF")
float("infinity")
float("Infinity")
创建一个持有
float

对象

您还可以在 python

 中表示 
-∞

float("-inf")
float("-INF")
float("-Inf")
float("-infinity")
创建一个持有 -∞

的浮动对象

您可以执行算术运算

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

0
投票

总而言之,无穷大有两种定义。

对于正无穷

posVal1 = math.inf
posVal2 = float("inf")

对于负无穷

negVal1 = -math.inf
negVal2 = float("-inf")

0
投票

用途:

float('inf')

或者数学模块:

import math
math.inf

但是如果你打印它,它们都会返回

inf
,这证明
math
也使用
float('inf')

© www.soinside.com 2019 - 2024. All rights reserved.