MIT 6.00 牛顿法 Python 3

MIT 6.00 Newton's Method in Python 3

这是麻省理工学院 OCW 6.00 计算与编程入门的第二个问题集的一部分 Python。首先,我创建了一个函数来计算给定 x 值的多项式。然后是计算给定多项式的导数的函数。使用这些,我创建了一个函数来计算给定多项式和 x 值的一阶导数。

然后我尝试创建一个函数来估计公差 (epsilon) 内任何给定多项式的根。

测试用例位于预期输出的底部。

我是编程新手,也是 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个函数return正确答案,但是compute_root(牛顿法)似乎没有进入while循环,因为当我运行单元格print(iteration) 打印 0。我认为由于 if fguess > 0 and fguess < epsilon: 应该 return false 对于测试用例(语句 print(fguess) 打印 -13.2119),解释器会转到 else 并进入 while 循环,直到它找到一个在 0 的 epsilon 范围内的解决方案。

我尝试消除第一个 if else 条件,这样我只有一个 return 语句,但我遇到了同样的问题。

什么可能导致函数完全跳过 else case / while 循环?我被难住了!

感谢您寻找and/or帮助!

这似乎只是一个小疏忽。请注意 fguess 是如何打印出值为 -13.2119 的。在您的 while 条件中(在 compute_root 中的 else 中)您需要 fguess > 0 and fguess < epsilon,但未满足该条件,因此无需进一步执行任何操作,您无需迭代即可退出。

改为:

while fguess < 0 or fguess > epsilon:

会给你你所需要的:

-13.2119
7
0.806790753796352