这是麻省理工学院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个函数返回正确的答案,但是compute_root(Newton&#39;方法)似乎没有进入while
循环,因为当我运行单元格print(iteration)
打印0时我会想到由于if fguess > 0 and fguess < epsilon:
应该为测试用例返回false
(语句print(fguess)
打印-13.2119
),解释器将转到else
并输入while
}循环,直到找到epsilon为0的解决方案。
我尝试删除第一个if
else
条件,这样我只有一个return
语句,我遇到了同样的问题。
可能导致该函数完全跳过else
case / while
循环的原因是什么?我很难过!
感谢您寻找和/或帮助!
答案 0 :(得分:0)
这似乎只是一个小小的疏忽。请注意如何使用值-13.2119打印fguess
。在while
条件下(else
来自compute_root
),您需要fguess > 0 and fguess < epsilon
,这不符合要求,因此无需进一步操作,您可以在不进行迭代的情况下退出。
相反:
while fguess < 0 or fguess > epsilon:
会给你你需要的东西:
-13.2119
7
0.806790753796352