I want to find the greatest integer less than or equal to the kth root of n. I tried
int(n**(1/k))
But for n=125, k=3 this gives the wrong
I wonder if starting off with a method based on logarithms can help pin down the sources of rounding error. For example:
import math
def power_floor(n, k):
return int(math.exp(1.0 / k * math.log(n)))
def nth_root(val, n):
ret = int(val**(1./n))
return ret + 1 if (ret + 1) ** n == val else ret
cases = [
(124, 3),
(125, 3),
(126, 3),
(1, 100),
]
for n, k in cases:
print "{0:d} vs {1:d}".format(nth_root(n, k), power_floor(n, k))
prints out
4 vs 4
5 vs 5
5 vs 5
1 vs 1