I’m planning to use very big numbers in Python, but wonder if Python can handle very big numbers. The numbers are going to have up to 3,000 zeros.
And, how much bytes does a 1 with 3,000 zeros use?
Third question, how can I save a number as integer into a file with Python without having to str() it?
Python can store arbitrarily long integers using the
longtype and even lets you specifylongliterals by appending anLto them (e.g.0Lis alongzero, as opposed to just0which is anint). Even better, it automatically “promotes” numbers fromints tolongs when the result of a calculation is too large to be represented by anint.longis a full-fledged numeric type and is compatible with all Python numeric operations.If you need more than integers, then you want the
decimalmodule, which features aDecimaltype that provides real numbers of arbitrary size and precision, without the issues inherent to binary floating-point representations.The downside of both
longandDecimalis that they are slower thanintandfloat, respectively, because the latter have native hardware support. But doing math on large numbers somewhat slowly beats not being able to use such numbers at all.As for size,
intobjects are 12 bytes in 32-bit Python. This seemingly large size for what is internally a 32-bit quantity is due to Python’s “everything’s an object” approach. (I believe, but don’t quote me, that there’s 4 bytes for the value, 4 bytes for a pointer from the instance to the type, and 4 bytes for a reference counter, which is used to determine when an object can be garbage-collected. These fields may be larger on 64-bit versions of Python.)The size of a
longvaries, as they vary based on the number (plus object overhead), but the size of anylongvalue can be determined usingsys.getsizeof().