Reputation: 9
I will show you my problem with the help of this code:
from math import log
print(log(1000000, 10))
The result is:
5.999999999999999
I perfectly know that the problem occurs because computers use binary system and we use decimal.
I have already tried the Decimal
library, but it didn't help me. This code:
from decimal import Decimal
print(log(Decimal("1000000"), Decimal("10")))
was giving me the same
5.999999999999999
How to fix this problem?
Edited: I forgot to mention that the base isn't necessarily 10!
Upvotes: 0
Views: 89
Reputation: 6310
import sympy
print(sympy.log(1000000,10))
Outputs 6
.
But, to be honest, it's better to be aware of the limitations of computers to store floating-point numbers to finite accuracy and not try to circumvent it.
Upvotes: 2
Reputation: 4510
You should try log10 as the following one
from math import log10
result = log10(1000000)
if result.is_integer():
result = int(result)
print(result)
Upvotes: 0