【问题标题】:Newton's method with recursion in python牛顿法在python中的递归
【发布时间】:2018-04-09 07:58:09
【问题描述】:

所以我的学校代码遇到了问题。我不知道如何解决它。

这是我的代码。

"""
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()

【问题讨论】:

  • 请通过突出显示您的代码来格式化它,然后按 ctrl+k。另外,您具体需要什么帮助?我在这里没有看到任何问题。
  • 请正确格式化,很难阅读。
  • “遇到问题”是您愿意告诉我们的一切吗?如果您对问题保密,我们应该如何提供帮助?
  • 你没有给函数一个估计的初始值。
  • 您好 Heather,欢迎来到 StackOverflow。我不会因任何反对票而气馁,它们在第一个问题中很常见。你应该看看help centerHow to Ask。理想情况下,您的问题应该包括minimal reproducible example,您的问题大多如此!我建议的最大改进是明确说明您遇到的问题。您期望的输出是什么,它与您当前获得的输出有何不同?你有错误吗?如果是这样,您应该发布完整的错误消息,包括堆栈跟踪。 “这行不通”在这里往往得不到很好的接受。

标签: python python-3.x recursion newtons-method


【解决方案1】:

问题

错误在您的主程序中。你打电话给

newton(x,estimate)

estimate 未定义。当你调用它时,该函数期望它有一个值:主程序负责分配一个值。试试这个:

newton(x, x/2)

下一个问题

这会使您的程序陷入无限循环。当你重复时,你没有正确地做数学:

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

您的新估计应该是旧估计和商的平均值,而不是它们的总和。您必须将总和除以二。您将返回的结果除以二。试试这个:

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

现在你可以做一个简单的例子。您的程序还有一些其他问题,但我会将这些问题留给学生练习。玩得开心。

【讨论】:

  • 不值得我自己回答,但我注意到 float("") 上的“按回车键”模式将失败,并出现值错误,这进一步使 if x == "": 行不起作用.
  • 右...“作为练习留下”。您不能将空字符串转换为float
猜你喜欢
  • 1970-01-01
  • 2022-01-16
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
相关资源
最近更新 更多