|
查看: 1507|回复: 0
|
Newton-Raphson method(python)
[复制链接]
|
|
|
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个就算到了,我的算法有问题?
谢谢。 |
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|