函數compute_root使用牛頓的逐次逼近方法來找到多項式零點的足夠好的近似值(這裏存在問題)。函數evalPoly計算特定x值處的多項式的值,並且函數ddx2計算多項式的導數。TypeError:'NoneType'對象不可迭代。爲什麼我會得到這個錯誤?
poly2 = (2,3,1,5) #poly2 represents the polynomial 5x^3+x^2+3x+1
def evalPoly(poly,x):
degree = 0
ans = 0
for index in poly:
ans += (index * (x**degree))
degree += 1
return ans
def ddx2(tpl):
lst = list(tpl)
for i in range(len(lst)):
lst[i] = lst[i]*i
if i != 0:
lst[i-1] = lst[i]
del lst[-1]
tpl = tuple(lst)
def compute_root(poly,x_0):
epsilon = .001
numGuesses = 1
if abs(evalPoly(poly,x_0)) <= epsilon:
ans = (evalPoly(poly,x_0),numGuesses)
print ans
return ans
else:
x_1 = x_0 - (evalPoly(poly,x_0)/evalPoly(ddx2(poly),x_0))
# This is Newton's method of getting progressively better/
# "guesses"
compute_root(poly,x_1)
x_0 = x_1
numGuesses += 1
return x_0
return poly
compute_root(poly2,2) #Here I call the function *compute_root*
當我調用該函數我得到這個錯誤:
Samuels-MacBook:python barnicle$ python problemset2.py
Traceback (most recent call last):
File "problemset2.py", line 160, in <module>
compute_root(poly2,x_0)
File "problemset2.py", line 156, in compute_root
x_1 = x_0 - (evalPoly(poly,x_0)/evalPoly(ddx2(poly),x_0))
File "problemset2.py", line 126, in evalPoly
for index in poly:
TypeError: 'NoneType' object is not iterable
我知道Python函數返回默認無。我認爲產生錯誤的原因是值無正在傳入參數poly in evalPoly。這是爲什麼發生?
我覺得包括一切,即使是功能ddx2(在這個例子中還沒有被調用)是謹慎的,因爲我不知道你是否需要它。我知道compute_root需要很多工作,這只是第一步。謝謝!!!
UPDATE !!!
。已經引起了我的注意,我得到的錯誤,因爲我的功能ddx2缺少一個返回值,所以這是當然的返回值沒有,這當然是不迭代。謝謝!!
UPDATE2 !!!
我在這裏有我的完整工作計劃,希望它可以幫助別人。我在這花了很多時間。這是麻省理工學院開放式課件的電氣工程與約翰·加塔教授計算機科學6.00sc,習題集2.
poly5 = (-13.39, 0.0, 17.5, 3.0, 1.0) # represents the polynomial:
# x^4+3x^3+17.5x^2-13.39
def evalPoly(poly,x):
degree = 0
ans = 0
for index in poly:
ans += (index * (x**degree))
degree += 1
return float(ans)
return degree
def ddx2(tpl):
lst = list(tpl)
for i in range(len(lst)):
lst[i] = lst[i]*i
if i != 0:
lst[i-1] = lst[i]
del lst[-1]
tpl = tuple(lst)
return tpl
def compute_root(poly,x_0,numGuesses):
epsilon = .001
ans = []
if abs(evalPoly(poly,x_0)) <= epsilon:
ans.append(x_0)
ans.append(numGuesses)
ans = tuple(ans)
print ans
return ans
else:
numGuesses += 1
x_0 = x_0 - (evalPoly(poly,x_0)/evalPoly(ddx2(poly),x_0))
compute_root(poly,x_0,numGuesses)
compute_root(poly5,.1,1)
輸出: 塞繆爾-的MacBook:蟒蛇barnicle $蟒蛇problemset2.py (0.806790753796352,8)
這個程序(這是一個程序?)只能找到一個真正的根,如果存在的話,但我認爲這是足夠的一個練習。