對于 Newton-Raphson 方法,我被要求撰寫一個回圈來呼叫該函式,直到它收斂,以便 x(n) 和 x(n 1) 的值相差小于一個小數 e=10^ -8,但是,我不太確定如何創建這個回圈。
到目前為止,這是我的代碼
def newton_step(f, fp, x0):
return x0-(f(x0)/fp(x0))
import numpy as np
def f(x):
return x**3 x**2 2
def fp(x):
return 3*x**2 2*x
x = newton_step(f, fp, (x0))
count = 0 #to count the number of iterations required to satisfy the condition
while (x0 - x) <= 10**-8:
x0 = newton_step(f, fp, (x0))
count = 1
print(x0, x)
uj5u.com熱心網友回復:
看起來您的比較運算子向后,請嘗試:
while (x0 - x) > 10**-8:
以便它會回圈,繼續while差異greater than 10^-8(一旦它小于該值就跳出回圈)
此外,您需要確保您的代碼x0在回圈之前設定了初始值(因此有一些比較)
uj5u.com熱心網友回復:
我可以看到您的代碼至少有 2 個問題 -
- 你不更新
x - 如果
x0<x那么回圈將結束,但它們可以有更多的不同10^-8 - 錯誤條件
總而言之,我會改變回圈 -
while abs(x0-x) >= 10**-8:
new_x = newton_step(f, fp, (x0))
x = x0
x0 = new_x
count =1
print(x0, x)
uj5u.com熱心網友回復:
只要差異較小,您的 while 回圈就會運行,但只要差異較大,它就會運行。更改while (x0 - x) <= 10**-8為while (x0 - x) >= 10**-8。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328850.html
上一篇:如何洗掉列中的部分字串值?
