首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python 3中的MIT 6.00牛顿法

Python 3中的MIT 6.00牛顿法
EN

Stack Overflow用户
提问于 2016-09-18 00:18:53
回答 1查看 664关注 0票数 0

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

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

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

我是编程新手,也是python新手,所以我在代码中包含了一些注释,以解释我认为代码应该做些什么。

代码语言:javascript
运行
复制
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循环?我被难住了!

感谢您的关注和/或帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-18 00:37:50

这似乎只是一个小小的疏忽。注意fguess是如何以-13.2119的值打印出来的。在您的while条件中(在来自compute_rootelse中),您需要fguess > 0 and fguess < epsilon,这是不满足的,因此不会进一步执行任何操作,并且您不需要迭代就退出了。

而是:

代码语言:javascript
运行
复制
while fguess < 0 or fguess > epsilon:

将为您提供所需的内容:

代码语言:javascript
运行
复制
-13.2119
7
0.806790753796352
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39549024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档