【发布时间】:2017-01-25 17:13:50
【问题描述】:
这是 MIT OCW 6.00 Intro to Computation and Programming using Python 的第二个问题集的一部分。首先,我创建了一个函数,用于计算给定 x 值的多项式。然后是计算给定多项式导数的函数。使用这些,我创建了一个函数,用于计算给定多项式和 x 值的一阶导数。
然后我尝试创建一个函数来估计任何给定多项式在公差 (epsilon) 内的根。
测试用例在底部,有预期的输出。
我是编程新手,也是 python 新手,所以我在代码中包含了一些 cmets 来解释我认为代码应该做什么。
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: 应该返回 @ 987654325@ 用于测试用例(语句print(fguess) 打印-13.2119),解释器将转到else 并进入while 循环,直到找到在ε 为0 内的解决方案。
我已经尝试消除第一个 if else 条件,这样我只有一个 return 语句并且我遇到了同样的问题。
什么可能导致函数完全跳过 else case / while 循环?我被难住了!
感谢您的关注和/或帮助!
【问题讨论】:
-
一个小而重要的观察:您不会访问任何数组的第一个(索引为
0的元素)。它应该是for i in range (len(poly)):而不是for i in range (1, len(poly)):。更改多项式和导数计算方法中的代码以反映这一点。 -
你应该自己做题集。
-
它应该是
abs(fguess) < epsilon作为根的条件。目前您排除-epsilon < fguess < 0作为近似解决方案。 -
@EvilTak:不,这些循环对于多项式求值是正确的。微分系数的构造。
-
Padraic,我感谢您对学术诚信的奉献,但由于资源有限,我决定遵循该政策:来自 EdX 协作指南:“可以让某人向您展示解决方案的几个步骤,其中你已经被困了一段时间,当然前提是你先尝试自己解决它,但没有成功。”来自 ocw.mit.edu 上的协作政策:“我们的政策很简单:除非作业本身另有说明,否则请随意在所有单独的问题集上相互协作,但请注意您与谁合作。”谢谢!
标签: python python-3.x newtons-method