Inaccurate Logarithm in Python

前端 未结 9 1989
甜味超标
甜味超标 2020-12-04 01:37

I work daily with Python 2.4 at my company. I used the versatile logarithm function \'log\' from the standard math library, and when I entered log(2**31, 2) it returned 31.0

9条回答
  •  星月不相逢
    2020-12-04 02:15

    If you wish to calculate the highest power of 'k' in a number 'n'. Then the code below might be helpful:

    import math
    answer = math.ceil(math.log(n,k))
    while k**answer>n:
        answer-=1
    

    NOTE: You shouldn't use 'if' instead of 'while' because that will give wrong results in some cases like n=2**51-1 and k=2. In this example with 'if' the answer is 51 whereas with 'while' the answer is 50, which is correct.

提交回复
热议问题