麻省理工学院6.00《python3》中的牛顿法

2024-05-16 05:12:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这是麻省理工学院OCW6.00使用Python计算和编程简介的第二个问题集的一部分。首先计算一个给定的多项式I的值。然后是一个计算给定多项式导数的函数。使用这些,我创建了一个函数,计算给定多项式和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循环,直到找到0的epsilon范围内的解决方案。在

我试着消除第一个ifelse条件,这样我只有一个return语句,而且我得到了相同的问题。在

是什么原因导致函数完全跳过elsecase/while循环?我被难住了!在

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


Tags: andthe函数answerforreturnrootevaluate
1条回答
网友
1楼 · 发布于 2024-05-16 05:12:50

这似乎只是一个小小的疏忽。请注意fguess是如何以-13.2119的值打印的。在您的while条件下(在else来自compute_root)您需要{},这是不满足的,因此不做任何进一步的操作,不经过迭代就退出。在

取而代之的是:

while fguess < 0 or fguess > epsilon:

将满足您的需要:

^{pr2}$

相关问题 更多 >