python中带递归的牛顿法

2024-04-18 13:40:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在学校的守则上遇到了问题。我不知道怎么修。在

这是我的密码。在

"""
Convert Newton’s method for approximating square roots in Project 1 to
a recursive function
named newton. (Hint: The estimate of the square
root should be passed as a second
argument to the function.)"""


import math
def newton(x, estimate):
    if abs (x-estimate ** 2) <= 0.000001:
            return estimate
    else:
        estimate = newton(x, (estimate + x/estimate)) /2
    return estimate                      
def main():
    while True:
        x = float(input('Enter a positive number or enter/return key to quit: '))
        if x == "":    
                break
        print("Newtons estimate of the sqaure root of ", x, "is: ", newton(x,estimate))
        print("The True value of the square root is: ", math.sqrt(x))
main()

Tags: ofthetotruereturnifmaindef
1条回答
网友
1楼 · 发布于 2024-04-18 13:40:01

问题

错误在主程序中。你打电话来

newton(x,estimate)

但是estimate未定义。函数期望在您调用它时它有一个值:主程序负责分配一个值。试试这个:

^{pr2}$

下一个问题

这会使程序陷入无限循环。当您再次出现时,您没有正确计算:

estimate = newton(x, (estimate + x/estimate)) /2

你的新估计值应该是旧值和商的平均值,而不是它们的和。你得把总数除以2。你把返回的结果除以2。试试这个:

estimate = newton(x, (estimate + x/estimate)/2)

现在你可以做一个简单明了的例子。你的课程还有一些其他的问题,但我将把这些留给学生练习。玩得高兴。在

相关问题 更多 >