编程牛顿法python3.6

2024-03-28 11:34:43 发布

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

对于我的作业,我们被要求创建一个程序,在其中计算牛顿法。有很多技术我们还没有学会,这就是为什么我只限于如何设计我的代码。在

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

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

今晚就要交了…我之前误解了作业,所以我以为我已经搞定了。请帮忙!在


Tags: oftheinforinputmaineval作业
1条回答
网友
1楼 · 发布于 2024-03-28 11:34:43

我不打算给你全部答案,因为这看起来像是一个家庭作业问题,但你的课程的核心是:

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

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

相关问题 更多 >