Python 的一体化无限价值。可以与任何物体进行比较。
float('inf')
和float('-inf')
。然而,这些只是代表浮点无穷大值。我想创建一个可以与任何类似对象进行比较的类。inf
相比,编写float('inf')
很笨拙pow(1, float('inf'))
返回 1,而它应该是未定义的。在无穷大中,此操作返回TypeError
。只需从 pypi 获取包:
pip 安装无穷大
支持的Python版本:
Infinity
类支持丰富的比较方法:
>> > import sys
>> > from datetime import datetime
>> > from infinity import inf
>> > 3 < inf
True
>> > datetime ( 2000 , 2 , 2 ) < inf
True
>> > - inf < inf
True
>> > inf == inf
True
>> > - inf == - inf
True
它还支持算术运算符:
>> > inf + inf
inf
>> > - inf - inf
- inf
>> > inf + 3
inf
>> > inf + datetime ( 2000 , 2 , 2 )
inf
>> > 5 / inf
0
>> > 3 / - inf
0
>> > pow ( inf , 0.5 )
inf
以下操作会引发TypeError
异常:
>> > inf - inf
Traceback ( most recent call last ):
...
TypeError : unsupported operand type ( s ) for - : 'Infinity' and 'Infinity'
>> > - inf + inf
Traceback ( most recent call last ):
...
TypeError : unsupported operand type ( s ) for + : 'Infinity' and 'Infinity'
>> > inf / inf # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback ( most recent call last ):
...
TypeError : unsupported operand type ( s ) for / : 'Infinity' and 'Infinity'
>> > inf * 0
Traceback ( most recent call last ):
...
TypeError : unsupported operand type ( s ) for * : 'Infinity' and 'int'
>> > pow ( inf , 0 ) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback ( most recent call last ):
...
TypeError : unsupported operand type ( s ) for ** or pow (): 'Infinity' and 'int'
>> > pow ( 1 , inf ) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback ( most recent call last ):
...
TypeError : unsupported operand type ( s ) for ** or pow (): 'int' and 'Infinity'
无穷大对象可以强制转换为各种类型:
>> > float ( inf ) == float ( 'inf' )
True
>> > float ( - inf ) == float ( '-inf' )
True
>> > str ( inf )
'inf'
>> > str ( - inf )
'-inf'
>> > bool ( inf )
True
>> > bool ( - inf )
True