6

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))
Bikramjeet Singh
  • 681
  • 1
  • 7
  • 22
Saisiot
  • 71
  • 3

2 Answers2

3

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?.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
2
  1. Yes, the documentation says so explicitly.
  2. 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))
    
Itamar Mushkin
  • 2,803
  • 2
  • 16
  • 32