Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : arbitrary precision with floats

I tried to compute math.exp(9500) but encountered an OverflowError: math range error (it's roughly 6.3e4125). From this question it seems like it's due to a too large float, the accepted answer says "(...) is slightly outside of the range of a double, so it causes an overflow".

I know that Python can deal with arbitrarily large integers (long type), is there a way to deal with arbitrarily large floats in the same manner ?

Edit : my original question was about using integers for calculating exp(n) but as Eric Duminil said, the simplest way to do that would be 3**n which doesn't provide any useful result. I know realize this question might be similar to this one.

like image 388
potato Avatar asked Sep 18 '26 08:09

potato


1 Answers

Here's another way to calculate the result with Python:

exp(9500)

is too big.

But log10(exp(9500)) isn't. You cannot calculate it this way in Python, but log10(exp(9500)) is log(exp(9500))/ln(10), which is 9500/ln(10):

>>> from math import log
>>> 9500/log(10)
4125.797578080892
>>> int(9500/log(10))
4125
>>> 10**(9500/log(10) % 1)
6.274484934896202

This way, you can calculate that exp(9500) is 6.27448493 * 10**4125 in plain Python, without any library!

like image 127
Eric Duminil Avatar answered Sep 19 '26 21:09

Eric Duminil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!