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

來源:互聯網
上載者:User
一、引言

這是我在學習 《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 sysprint(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 sysprint(sys.maxsize)

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

9223372036854775807

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

print(float('inf'))

上述運算式輸出:

inf

用於表達無限大的浮點數值。 三、總結

其實就是兩句話:

sys.maxsize

float(‘inf’)

簡單易記,方便使用:)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.