Today, I used math.log()
function to get the logarithm of 4913 to the given base 17. The answer is 3, but when I ran the code below, I got 2.9999999999999996.
1) Is it because math.log(x, b)
's calculation is log(x) / log(b)
?
2) Is there any solution to get the correct answer 3?
import math
print(math.log(4913,17))
you could use the gmpy2
library:
import gmpy2
print(gmpy2.iroot(4913, 3))
# (mpz(17), True)
print(gmpy2.iroot(4913 + 1, 3))
# (mpz(17), False)
which tells you the result and whether or not it is exact.
also have a look at Log precision in python and Is floating point math broken?.
Another solution is to use the Decimal class, from the "decimal" library:
import math
from decimal import Decimal, getcontext
getcontext().prec = 6
Decimal(math.log(4913))/Decimal(math.log(17))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With