I'm looking to compute floor(log(n,b))
where n
and b
are both integers. Directly implementing this function fails for even slightly large values of n
and b
# direct implementation
def floor_log(n,b):
return math.floor(math.log(n,b))
For example, floor_log(100**3, 100)
evaluates to 2
instead of the correct value 3
.
I was able to come up with a working function which repeatedly divides until nothing remains
# loop based implementation
def floor_log(n,b):
val = 0
n = n // b
while n > 0:
val += 1
n = n // b
return val
is there a faster or more elegant way of obtaining this solution? Perhaps using built-in functionality?
The floor function is discontinuous at every integer. [1] \lfloor x floor \le x < \lfloor x floor +1 ⌊x⌋ ≤ x < ⌊x⌋+1 is often enough to solve basic problems involving the floor function. ⌊ 0.5 + ⌊ x ⌋ ⌋ = 20.
If your answer is in the form a + b. a+b. a+b. \lfloor \cdot floor ⌊⋅⌋ denotes the floor function. Definite integrals and sums involving the floor function are quite common in problems and applications. The best strategy is to break up the interval of integration (or summation) into pieces on which the floor function is constant.
Math class in Java (java.lang.Math) is a library which holds the functions to calculate such values, like sin (), cos (), log () etc. But the log () method in Math class calculates the log to the base 10.
If you're taking a log base 2 of a binary number, you can even omit the multiplying by a constant, making it . Could anyone give a casual explanation of the difference between complexity classes and time complexity classes, and the differing need (s) each was conceived to address?
One way is to make your function self-correcting:
def floor_log(n,b):
res = math.floor(math.log(n,b))
return res + 1 if b**(res+1) == n else res
Or a bit more obscure:
def floor_log(n,b):
res = math.floor(math.log(n,b))
return res + (b**(res+1) == n)
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