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