본문 바로가기
Study/Language

[Python] 파이썬 int의 최대값은?

by jamiehun 2023. 2. 14.

목적 : 파이썬에 대한 기본적인 지식 함양

 

기술인터뷰를 보다가 python의 int의 범위는 어느정도 될까요? 라는 질문을 받았다.

평소 생각하지 못했던 내용이라 C언어의 4bytes로 유추해 '2의 32승의 데이터를 표현할 수 있을 것이라고 생각합니다.'로 말씀을 드렸다.

 

면접을 보고 다시 한번 찾아보니 파이썬은 int의 limit값이 따로 없다.

 

공식문서에 명확하게 나와 있다.

 

Integers have unlimited precision. (official)
In Python, value of an integer is not restricted by the number of bits and can expand to the limit of the available memory (geeksforgeeks)

 

좀 더 구체적으로 얘기하자면 python2에서는 int와 long int를 따로 썼는데

int의 경우 C style의 fixed-precision integer로 쓰였고, long은 arbitrary-precision integer로 쓰였다.

하지만 python3에 들어서는 int와 long int가 결합되어 int로 쓰이고 arbitrary-precision integer로 쓰이고 있다.

fixed-precision integer는 C 언어와 동일하게 4바이트 데이터형으로 쓰인다는 것은 알겠는데,

 

그렇다면 arbitrary-precision integer는 무엇일까?

 

Arbitrary-precision integer indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most arithmetic logic unit  (ALU) hardware, which typically offers between 8 and 64 bits of precision. (Wikipedia)

 

위의 위키피디아 내용과 같이 arbitrary-precision에서는 가용가능한 메모리에 의해 숫자가 표시가 제한된다.

(= 메모리가 허용하는 한 unlimited하게 보장한다.)

이는 위에서 말한 unlimited precision과 동일한 맥락이다. (주피터 노트북 참고)

 

하지만 여기서 주의할 점은 numpy를 쓸 때는 overflow가 일어날 수도 있다는 점이다. (numpy는 fixed-precision을 사용)

아래의 주피터 노트북을 참고하면 +1을 했을 때 음수의 값이 나오는 것을 알 수 있다.

하지만 여기서 mean 값은 제대로 찍히는데 이는 모든 Input 값을 float으로 바꾼 후

np.mean을 계산하기 때문에 overflow는 일어나지 않는다. (주피터 노트북2 참고)

 

 

[arbitrary-precision]

arbitrary-precision

 

[numpy_overflow]

numpy_overflow

 

 

[참고자료]

https://docs.python.org/3.8/library/stdtypes.html

https://www.geeksforgeeks.org/what-is-the-maximum-possible-value-of-an-integer-in-python/

https://mortada.net/can-integer-operations-overflow-in-python.html 

https://ahracho.github.io/posts/python/2017-05-09-python-integer-overflow/