Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong answer from math.log(python 3)

Tags:

python

math

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))
like image 971
Saisiot Avatar asked Mar 18 '19 13:03

Saisiot


2 Answers

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

like image 117
hiro protagonist Avatar answered Sep 30 '22 09:09

hiro protagonist


  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))
    
like image 36
Itamar Mushkin Avatar answered Sep 30 '22 09:09

Itamar Mushkin