1. 程式人生 > >Python 小技巧:Python3 表示最大整數值和浮點數值

Python 小技巧:Python3 表示最大整數值和浮點數值

一、引言

這是我在學習 《Python Algorithms 2nd》 一書中第 28 頁時候受到的啟發:

For intergral weights, you could use sys.maxint , even though it’s not guaranteed to be the greatest possbile value (long ints can be longer).

我們廢話少說,直接測試程式碼:

import sys
print(sys.maxint)

我們滿心期待著以為可以輸出最大的整數數值,結果發現報錯了:

Traceback (most recent call last):
File “”, line 1, in
AttributeError: module ‘sys’ has no attribute ‘maxint’

那麼,這是為什麼呢?

二、探索

中文社群有關這個問題的探索很少,於是我找到了 StackOverflow 上的外國友人的描述:

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any pratical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

也就是說,在新版本的發行版中,sys.maxint 已經被去掉了,因為對於整型數值再也沒有限制了。但是呢,標準又提供了 sys.maxsize 來表示一個大於任何我們實際工作中能夠表示的最大的整型數值。這個值正好與原來的 sys.maxint 相同。

那麼,就讓我們測試下:

import sys
print(sys.maxsize)

在我的機器上,執行結果為:

9223372036854775807

另外,想要表達最大的浮點數值,可以:

print(float('inf'))

上述表示式輸出:

inf

用於表達無限大的浮點數值。

三、總結

其實就是兩句話:

sys.maxsize

float(‘inf’)

簡單易記,方便使用:)