首页 > 解决方案 > 具有循环递归的牛顿法

问题描述

我这里的代码都弄清楚了。指示说“将项目 1 中用于逼近平方根的牛顿方法转换为名为 newton 的递归函数。(提示:平方根的估计值应作为函数的第二个参数传递。)” 我将如何计算这些根据我的代码这里的方向?

# Initialize the tolerance
TOLERANCE = 0.000001
def newton(x):
    """Returns the square root of x."""
    # Perform the successive approximations
    estimate = 1.0
    while True:
        estimate = (estimate + x / estimate) / 2
        difference = abs(x - estimate ** 2)
        if difference <= TOLERANCE:
            break
    return estimate
def main():
    """Allows the user to obtain square roots."""
    while True:
        # Receive the input number from the user
        x = input("Enter a positive number or enter/return to quit: ")
        if x == "":
             break
        x = float(x)
        # Output the result
        print("The program's estimate is", newton(x))
        print("Python's estimate is     ", math.sqrt(x))
if __name__ == "__main__":
    main()

标签: pythonrecursion

解决方案


本质上,您需要while True:在递归函数中转换部分代码,如下所示:

def newton(x, estimate):
    estimate = (estimate + x / estimate) / 2
    difference = abs(x - estimate ** 2)
    if difference > TOLERANCE:
        estimate = newton(x, estimate)
    return estimate

注意条件是如何不同的,因此您检查是否需要继续,在您不需要最终值之后,将执行递归并返回


推荐阅读