I'm writing some code to generate digits of the mathematical constant e (Eulers number), to any amount of precision.
from decimal import Decimal, getcontext
import decimal
s = 300_000
n = Decimal(1)
x = Decimal(1)
print("[+] Summing numbers...")
getcontext().prec = s
for i in range(s, 1, -1):
x *= i
n += x
result = (n / x) + Decimal(1.0)
it works with 200k iterations or less, but fails if I set the precision higher then that.
[+] Summing numbers...
Traceback (most recent call last):
File "D:\OneDrive\Desktop\PYTHON\py\trig\log\calc e\e1_2.py", line 12, in <module>
x *= i
decimal.Overflow: [<class 'decimal.Overflow'>]
>>>
How can I store very large numbers with python, that are hundreds of thousands of digits long, without throwing a decimal.Overflow error?
The decimal
module exists for decimal calculations. For calculations with arbitrary precision numbers, use int
and fractions.Fraction
.
from fractions import Fraction
s = 300_000
x = 1
n = 1
for i in range(s, 1, -1):
x *= i
n += x
result = Fraction(n, x) + 1
To specifically display the result with a given number of decimal digits, one can then format
the result as desired:
# Display approximate value (the raw value is huge)
print(float(result)) # 2.718281828459045
# Display value with a given number of decimal digits
print(format(result, '.64g')) # 2.7182818284590452353602874713526624977572470936999595749669676277
Note that since Python 3.11, there is a limit on the digits that can be used in formatting which also applies here. Use sys.set_int_max_str_digits
to increase the limit (a value of 0
disables the limit).