佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 1507|回复: 0

Newton-Raphson method(python)

[复制链接]
发表于 16-4-2009 08:55 PM | 显示全部楼层 |阅读模式
Implement Newton-Raphson by completing the following skeleton:
def findRoot(n, c):
      """
      Return an approximate root of the equation (x^n - c = 0). The value of x
      that is returned should be such that (x^n - c) differs from 0 by no more
      than 0.001.
      This function also prints a message showing the number of iterations needed

      to find the root.

      """

      # Your code goes here.

Newton-Raphson requires us to know the first derivative of f(x) = xn - c, which is n xn-1. Recall that in Python, xn
is written x**n.
The solution that Newton-Raphson gives may depend on the initial guess you used. In your code, please use c/2
as your first guess.
Here is a sample use of findRoot:
>>> findRoot(2, 25) # Computes sqrt(25)

(Number of iterations: 4)

5.0000129530486843

>>> findRoot(2, 2) # Computes sqrt(2)

(Number of iterations: 3)

1.4142156862745099

>>> findRoot(4, 143) # Computes fourth root of 143

(Number of iterations: 14)

3.458071842417946

It's fine if your solutions differ slightly from these sample outputs.
-------------------------------------------------------------------------------------------
我的答案

def findRoot(n, c):
    xZero = float (c/2)
    xFirst = xZero - ((xZero**n - c) / (n*xZero**n-1))
    xFirstOld = xFirst
    xZero = xFirst
    xFirst = xZero - ((xZero**n - c) / (n*xZero**n-1))
    count = 0

    while xFirstOld != xFirst:
        xFirstOld = xFirst
        xZero = xFirst
        xFirst = xZero - ((xZero**n - c) / (n*xZero**n-1))
        count += 1

    print xFirst
    print count

findRoot(4, 143)
----------------------------------------------------------------------------------------------------------
这个是python的题目
请问我做得对吗?
及,我的findRoot(4,143)用了343个loop才算到,那个例子用14个就算到了,我的算法有问题?
谢谢。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 14-12-2025 10:22 AM , Processed in 0.102885 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表