这是麻省理工学院开放式课程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 (牛顿方法)似乎没有进入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
循环?我被难住了!
感谢您的关注和/或帮助!
发布于 2016-09-17 16:37:50
这似乎只是一个小小的疏忽。注意fguess
是如何以-13.2119的值打印出来的。在您的while
条件中(在来自compute_root
的else
中),您需要fguess > 0 and fguess < epsilon
,这是不满足的,因此不会进一步执行任何操作,并且您不需要迭代就退出了。
而是:
while fguess < 0 or fguess > epsilon:
将为您提供所需的内容:
-13.2119
7
0.806790753796352
https://stackoverflow.com/questions/39549024
复制相似问题