使用递归计算Log in Python

时间:2018-04-22 07:13:25

标签: python recursion

def recursivelog(n, x, b):
    assert n >= 0
    assert x >= 1
    assert isinstance(b, int) 
    assert b >= 2
    float(x)  # this statement does not change x so is useless here
    if(x < b):
        return 0
    else:
        return 1+ recursivelog(n-1, x/b, b)

n表示步骤数(或递归调用)

x计算对数的数字

b对数的基数

虽然结果将舍入到最接近的正整数,如

>>> recursivelog(100, 3)
4

如何获得实数结果?

2 个答案:

答案 0 :(得分:0)

您可以做的一件事就是在这里使用二进制搜索。 以下内容应该有效:

myClass{    
    height: calc(50% - 33.5px);
    width: heightReturnedValue*1.3
}

您可以进行一些调整以改善。如果您担心效率,可以使用算法直到函数返回小于基数的值。您应该使用它来计算小于基数的值的日志。

答案 1 :(得分:0)

递归算法背后的想法是让它们递归直到它们达到基本情况。截断递归算法可能会导致意外的结果和错误,尤其是在存在未决计算时。

可以(应该)计算整数对数,而不必处理浮点数。考虑对数的实际含义:log(x, base) == c暗示base ** c == x。在非专业术语中,一个人将base乘以x以获得x 的必然结果,需要分割多少次{{ 1}} base在其他地方获取c

在你的问题中,你想要整数对数,所以,我们执行整数除法。这是你重新提出的问题: 需要多少次({整数除法)xbase以获得c

有了这个,程序随之而来:

def rec_ilogn(x, n):
    """return the integer logarithm of x to base n"""
    assert x > 0, "Real logarithms are only defined for x > 0"
    if x < n:
        return 0
    return 1 + rec_ilogn(x//n, n)

现在测试代码:

>>> from math, import log
>>> ilogn = lambda x, n: int(log(x)/log(n)) # integer log(x, base)
>>> print([ilogn(i, 10) for i in range(1, 1000)] == [rec_ilogn(i, 10) for i in range(1, 1000)])
True