【问题标题】:Programming Newton's Method Python 3.6编程牛顿法 Python 3.6
【发布时间】:2017-06-28 06:24:30
【问题描述】:

对于我的任务,我们需要创建一个计算牛顿法的程序。有很多技术我们还没有学到,这就是为什么我只限于如何设计我的代码。

我特别需要帮助,根据我用于迭代次数的输入,让实际的牛顿法循环通过,但任何建议都会很乐意接受。

def main():
    print("This program computes square roots through the Newton method")
    x = eval(input("Enter a number to calculate the square root of: "))
    r = eval(input("How many iterations should I use?: "))

    for i in range(1, r+1):
        guess = x/2
        for n in (1, r+1):
            n = (guess + (x/guess))/2   # Newton's Method formula
        import math
    y = math.sqrt(x)  # actual square root value

    for i in range(1, r+1):
        print(i, n, n-y)  # attempt at extra credit

    print("My guess for the square root of", x, "is", n)
    print("The difference between my guess and the actual result is:", n-y)


main()

这是今晚到期的……我之前误解了作业,所以我以为我已经弄清楚了。请帮忙!

【问题讨论】:

  • 为什么要循环导入?将import math 移动到文件顶部。
  • 你想用for n in (1, r+1):完成什么?
  • 我正在尝试使用 for 循环,以便牛顿公式将 r 次。我正在使用 r+1 表示法,因此答案将从 [1,n] 而不是从 0 打印出来。如果有帮助,我可以发布公式的输出应该是什么样子。不确定这是否有意义,但我会尽力澄清。感谢您的关注。
  • 好吧,对于一个你只需要一个 for 循环。第二个 for n in (1, r+1) 不是 r 次循环,因为您没有包含范围。它只是在1r+1 上循环,并将您尝试做的事情覆盖到n。您也不需要在循环中计算“猜测”。
  • 你需要用n的内容修改'n'。所以尝试一下,也许 n = (n + x/n)/2 来更新 n?

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


【解决方案1】:

我不会给你完整的答案,因为这看起来像是一个家庭作业问题,但你程序的核心很简单:

for i in range(r):
    n = (n + x/n)/2

想想 n 应该从什么开始。考虑一下如何在生成答案时打印出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2013-10-17
    • 2017-05-05
    • 2018-11-21
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多