迭代牛顿法
我有一段代码是用来解决牛顿法的问题,针对一个给定的多项式和初始猜测值。我想把它变成一个迭代的过程,因为牛顿法本身就是一个迭代的过程。这个程序应该一直运行,直到输出值“x_n”变得稳定不变。最后的“x_n”值就是实际的根。此外,在我的算法中使用这个方法时,它应该始终产生一个在0到1之间的正根。那么,把负的输出(根)转换成正数会有什么不同吗?谢谢。
import copy
poly = [[-0.25,3], [0.375,2], [-0.375,1], [-3.1,0]]
def poly_diff(poly):
""" Differentiate a polynomial. """
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
""" Apply a value to a polynomial. """
sum = 0.0
for term in poly:
sum += term[0] * (x ** term[1])
return sum
def poly_root(poly):
""" Returns a root of the polynomial"""
poly_d = poly_diff(poly)
x = float(raw_input("Enter initial guess:"))
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
print x_n
if __name__ == "__main__" :
poly_root(poly)
2 个回答
0
import copy
poly = [[1,64], [2,109], [3,137], [4,138], [5,171], [6,170]]
def poly_diff(poly):
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
sum = 0.0
for term in poly:
sum += term[0] * (x ** term[1])
return sum
def poly_root(poly):
poly_d = poly_diff(poly)
x = float(input("Enter initial guess:"))
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
print (x_n)
if __name__ == "__main__" :
poly_root(poly)
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
1
首先,在poly_diff这个函数里,你需要检查一下指数是不是零。如果是零的话,就直接把这个项从结果中去掉。否则,导数在零的时候就会变得不明确。
def poly_root(poly):
""" Returns a root of the polynomial"""
poly_d = poly_diff(poly)
x = None
x_n = float(raw_input("Enter initial guess:"))
while x != x_n:
x = x_n
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
return x_n
这样就可以了。不过,我觉得对于某些多项式来说,可能会出现无法结束的情况,这主要是因为浮点数的舍入误差。这样可能会导致计算进入一个循环,反复出现的结果只是在最末尾的几位数字上有些许不同。你可以在变化的百分比达到某个下限时结束,或者在进行了一定次数的迭代后结束。