迭代牛顿的方法

时间:2011-08-10 10:52:22

标签: python

我有这个代码来解决给定多项式和初始猜测值的牛顿方法。我想变成牛顿方法实际上是一个迭代过程。程序应该保持运行直到输出值“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 :(得分: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

应该这样做。但是,我认为由于浮点舍入误差,某些多项式可能无法终止。它可能最终处于仅在最低有效位上不同的近似重复周期。您可以在更改百分比达到下限或经过多次迭代后终止。

答案 1 :(得分: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)