這是麻省理工學院OCW 6.00使用Python進行計算和編程的第一個問題集的一部分。首先,我創建了一個函數來評估給定x值的多項式。然後是計算給定多項式的導數的函數。使用這些函數,我創建了一個函數,用於評估給定多項式和x值的一階導數。麻省理工學院6.00 Python中的牛頓法3
然後,我試圖創建一個函數來估計任何給定的多項式在容差(ε)內的根。
測試用例處於預期輸出的底部。
我是新來的編程和新的Python,所以我在代碼中包含了一些註釋來解釋我認爲代碼應該做的事情。
def evaluate_poly(poly, x):
""" Computes the polynomial function for a given value x. Returns that value."""
answer = poly[0]
for i in range (1, len(poly)):
answer = answer + poly[i] * x**i
return answer
def compute_deriv(poly):
"""
#Computes and returns the derivative of a polynomial function. If the
#derivative is 0, returns (0.0,)."""
dpoly =()
for i in range(1,len(poly)):
dpoly = dpoly + (poly[i]*i,)
return dpoly
def df(poly, x):
"""Computes and returns the solution as a float to the derivative of a polynomial function
"""
dx = evaluate_poly(compute_deriv(poly), x)
#dpoly = compute_deriv(poly)
#dx = evaluate_poly(dpoly, x)
return dx
def compute_root(poly, x_0, epsilon):
"""
Uses Newton's method to find and return a root of a polynomial function.
Returns a float containing the root"""
iteration = 0
fguess = evaluate_poly(poly, x_0) #evaluates poly for first guess
print(fguess)
x_guess = x_0 #initialize x_guess
if fguess > 0 and fguess < epsilon: #if solution for first guess is close enough to root return first guess
return x_guess
else:
while fguess > 0 and fguess > epsilon:
iteration+=1
x_guess = x_0 - (evaluate_poly(poly,x_0)/df(poly, x_0))
fguess = evaluate_poly(poly, x_guess)
if fguess > 0 and fguess < epsilon:
break #fguess where guess is close enough to root, breaks while loop, skips else, return x_guess
else:
x_0 = x_guess #guess again with most recent guess as x_0 next time through while loop
print(iteration)
return x_guess
#Example:
poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39
x_0 = 0.1
epsilon = .0001
print (compute_root(poly, x_0, epsilon))
#answer should be 0.80679075379635201
第3個函數返回正確的答案,但compute_root(牛頓法)似乎並沒有進入while
循環,因爲當我運行單元print(iteration)
打印0。我會想,既然if fguess > 0 and fguess < epsilon:
應爲返回false
測試用例(聲明print(fguess)
打印-13.2119
),解釋器會去else
並進入while
循環,直到找到一個解決方案,是0
小量內我試圖消除第一if
else
康迪所以我只有一個return
聲明,我也遇到了同樣的問題。
什麼可能導致函數跳過else
case/while
循環?我很難過!
感謝您的期待和/或幫助!
一個小而顯著觀察:你不(與索引元素'0')訪問的第一個任意陣列。它應該是'我在範圍內(len(poly)):'not'因爲我在範圍內(1,len(poly)):'。更改多項式和導數計算方法中的代碼以反映此情況。 – EvilTak
你應該自己做問題集。 –
它應該是'abs(fguess)ε'作爲根的條件。目前,您將'-epsilon
LutzL