為什麼c++的整數會溢出,而Python的整數不會溢出呢?

我覺得Python的整數不會溢出好,而c++太麻煩了,還要考慮溢出的問題!


在python2.7中,表示整數的有int和long兩個類型。int類型和C++的int類似,都是一個固定位數的數;long則是一個理論上可以存儲無限大數的數據類型。當你的數大到可能溢出時,python就會機智的幫你轉換成long,這樣就避免了溢出。而python3之後整數只有一個可以放任意大數的int了。可是無論哪種,都是採用了特殊的方法實現了不會溢出的大整數。

整數溢出的本質就是空間不夠無法完整存放數據,因此對付溢出的思路就是加空間,1Byte hold不住上2Byte,2Byte不行再加。python中的大整數就是用了這個原理,把一個格外大的數拆分成若干個byte,然後把每個byte存下來。然後再針對多字整型實現一套操作,放在用戶面前的就是一個用起來很省心的絕對沒有溢出的good int了。但相應的,由於每次運算要處理多個byte,效率下降是必然的了

===================我是分割線=====================================

如果題主還是好奇python中具體是怎麼做到的,可以去看看源碼,在py2中叫long,py3中叫int。另外,我最近啃python也略有所得,都寫在博客中,若題主有興趣可以去看看哈^ ^


所以Python慢


I"m here to settle this question.

Using a float allows us to represent a much larger range of values than a 32-bit int, but the amount of precision is still fixed. In fact, a computer stores floating point numbers as a pair of fixed-length(binary) integers. One integer represents the string of digits in the value, and the second represent the exponent that keeps track of where the whole part ends and the fractional part begins.

Fortunately, Python has a better solution for large, exact values. A Python int is not a fixed size, but accommodate whatever value it holds. The only limit is the amount of memory the computer has available to it. When the value is small, Python can just use the computer"s underlying int representation and operations. When the values gets larger, Python automatically converts to a representation using more bits. Of course, in order to perform operations on larger numbers, Python has to break down the operations into smaller units that the computer hardware is able to handle. Sort of like the way you might do long division by hand. These operations will not be as efficient (they require more steps), but they allow our Python ints to grow to arbitrary size.(note: here is what @Intopass mentioned.)

from Python Programming: An introduction to computer science, John Zelle


推薦閱讀:

為什麼scanf()用cmd編譯可以通過,但用vs2015卻不能通過?
有那些值得學習的C/C++和Lua開發的項目源碼?
什麼是面向對象編程?它與面向過程編程的異同有哪些?
C++中為什麼有delete[]這種寫法?
關於指針數組的初始化的一個問題?

TAG:程序員 | 編程語言 | Python | 編程 | C |