I am trying to find the logarithm of a number to base 3 using python.
Here is the problem :
https://leetcode.com/problems/power-of-three/description/
I am using this code:
import math
math.log(k,3)
However, it is failing for some test cases like (there are some more test cases):
math.log(243,3)
#output
4.999999999999999
math.log(59049,3)
#output
9.999999999999998
I do not want to use round() as it will round other numbers which are not the powers of 3.
Here is the full code which I am using:
class Solution:
def isPowerOfThree(self, n: int) -> bool:
import math
k = abs(n)
if n<=0:
return False
return math.log(k,3) == int(math.log(k,3))
Note: I am looking for solutions involving logarithms. Please feel free to ask for any clarifications.
This is just typical floating-point error. Recall that when you write
math.log(x, 3), Python is actually calculating something likemath.log(x) / math.log(3), with both (natural) log calculations and the division having to be rounded to the nearestfloat.But if you do your math with
intinstead offloat, exactness is preserved.This checks if you can divide
nby 3 (without remainder) until the result is 1.