牛顿方法的意外输出

时间:2011-08-16 12:33:23

标签: python

我有这个代码用于解决牛顿方法,在最后一次迭代中,输出值出错了。当我在纸上手动检查时,这些值不应该是负数。据我所知,代码是正确的,但我无法弄清楚为什么它显示负值,最后的u值理想情况下应该是介于0和1之间的正值。这是代码:

import copy
import math

tlist = [0.0, 0.07, 0.13, 0.15, 0.2, 0.22] # list of start time for the phonemes

w = 1.0

def time() :
    t_u = 0.0
    for i in range(len(tlist)- 1) :
        t_u = t_u + 0.04 # regular time interval
        print t_u
        print tlist[i], ' ' , tlist[i+1], ' ', tlist[i -1]
        if t_u >= tlist[i] and t_u <= tlist[i + 1] :
            poly = poly_coeff(tlist[i], tlist[i + 1], t_u)
            Newton(poly) 
        else :
            poly = poly_coeff(tlist[i - 1], tlist[i], t_u)
            Newton(poly) 

def poly_coeff(start_time, end_time, t_u) :
    """The equation is k6 * u^3 + k5 * u^2 + k4 * u + k0 = 0. Computing the coefficients for this polynomial."""
    """Substituting the required values we get the coefficients."""
    t0 = start_time
    t3 = end_time
    t1 = t2 = (t0 + t3) / 2
    w0 = w1 = w2 = w3 = w
    k0 = w0 * (t_u - t0)
    k1 = w1 * (t_u - t1)
    k2 = w2 * (t_u - t2)
    k3 = w3 * (t_u - t3)
    k4 = 3 * (k1 - k0)
    k5 = 3 * (k2 - 2 * k1 + k0)
    k6 = k3 - 3 * k2 + 3 * k1 -k0 

    print k0, k1, k2, k3, k4, k5, k6
    return [[k6,3], [k5,2], [k4,1], [k0,0]]

def poly_differentiate(poly):
    """ Differentiate polynomial. """
    newlist = copy.deepcopy(poly)

    for term in newlist:
        term[0] *= term[1]
        term[1] -= 1

    return newlist

def poly_substitute(poly, x):
    """ Apply value to polynomial. """
    sum = 0.0 

    for term in poly:
        sum += term[0] * (x ** term[1])
    return sum

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value 
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly) 

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))

        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print x_n
    print "u: ", x_n
    return x_n

if __name__ == "__main__" :
    time()

最后一次迭代的输出如下,

其中k6 = -0.02,k5 = 0.03,k4 = -0.03且k0 = 0.0

0.2
0.2   0.22   0.15
0.0 -0.01 -0.01 -0.02 -0.03 0.03 -0.02
-0.166666666667
-0.0244444444444
-0.000587577730193
-3.45112269878e-07
-1.19102451449e-13
u: -1.42121180685e-26

初始猜测值为0.5,因此如果在多项式中替换,则输出为-0.005。

然后在分化多项式中再次使用相同的初始值。结果是-0.015。

现在这些值在牛顿方程中被替换,那么答案应该是0.166666667。但实际答案是负值。

谢谢。

2 个答案:

答案 0 :(得分:0)

啊,我现在看到了。

就像你说的那样,

float(poly_substitute(poly, x))

评估为-0.015。然后,

float(poly_substitute(poly_diff, x))

评估为-0.01。因此,替换这些值和x

x_n = 0.5 - ( (-0.015) / (-0.01) )
x_n = 0.5 - 0.6666666...
x_n = -0.166666...

您的手动数学是错误的,而不是代码。

答案 1 :(得分:0)

给定的多项式在x = 0处有一个解。代码工作正常。