python - Computing logarithm -
i must write function computes logarithm of number x
relative base b
(rounded down if answer not integer). wrote function it's not working
def mylog(x, b): result = 1 if b > x : result -= 1 return result elif x == b : return result else : result += 1 b *= result return mylog(x,b)
why multiplying base result , changing base? when determine base fits input number, should dividing number base. since division means final number 1 more, add 1 result of recursive call.
def mylog(x, b): result = 1 if b > x: result -= 1 return result elif x == b: return result else: x /= b return 1 + mylog(x, b)
example: mylog(32, 2):
32/2 = 16, add 1 answer
16/2 = 8, add 1 answer
...
answer = 5
some of code unnecessary though, , further edit this:
def mylog(x, b): if b > x: return 0 elif x == b: return 1 else: x /= b return 1 + mylog(x, b)
Comments
Post a Comment