使用Horner的方法找到P(x)和P'(x)

时间:2015-02-01 20:22:30

标签: python numerical-analysis

我的教科书给出了Horner方法的伪代码如下:

P(x) = a_n x n + a_n−1 x n−1 + ··· + a_1 x + a_0 = (x−x0)Q(x) + b0

INPUT degree n; coefficients a_0 , a_1 , . . . , a_n ; x0 .
OUTPUT y = P(x 0 ); z = P (x 0 ).
Step 1 Set y = a_n ; (Compute b n for P.)
           z = a_n . (Compute b n−1 for Q.)
Step 2 For j = n − 1, n − 2, . . . , 1
           set y = x0 * y + a_j ; (Compute b_j for P.)
                   z = x0 * z + y. (Compute b_j−1 for Q.)
Step 3 Set y = x0 + y + a_0 .
Step 4 OUTPUT (y, z);
       STOP.

现在我遇到的问题是伪代码中的下标似乎与公式中的下标不匹配

我做了一个python实现,但我得到的答案似乎错了,所以我稍微改了一下

def horner(x0, *a):
    '''
        Horner's method is an algorithm to calculate a polynomial at
        f(x0) and f'(x0)

        x0 - The value to avaluate
        a - An array of the coefficients

        The degree is the polynomial is set equal to the number of coefficients
    '''
    n = len(a)

    y = a[0]
    z = a[0]
    for j in range(1, n):
        y = x0 * y + a[j]
        z = x0 * z + y

    y = x0 * y + a[-1]

    print('P(x0) =', y)
    print('P\'(x0) =', z)

它运作得很好,但我需要在这方面有更多经验的人给它一次。

作为一个非常基本的测试,我采用了多项式2x ^ 4,其值为-2。

要在方法中使用它,我将其称为

horner(-2, 2, 0, 0 ,0)

对于这个非常简单的问题,输出确实看起来正确。由于f(x)= 2x ^ 4,然后f(-2)= -32,但这是我的实现给出不同结果的地方我的答案是肯定的

1 个答案:

答案 0 :(得分:0)

我发现了问题,我在这里添加了答案,因为它可能对未来的某人有用

首先,在算法中,循环必须达到n-1

def horner(x0, *a):
    '''
        Horner's method is an algorithm to calculate a polynomial at
        f(x0) and f'(x0)

        x0 - The value to avaluate
        a - An array of the coefficients

        The degree is the polynomial is set equal to the number of coefficients
    '''
    n = len(a)

    y = a[0]
    z = a[0]
    for j in range(1, n - 1):
        y = x0 * y + a[j]
        z = x0 * z + y

    y = x0 * y + a[-1]

    print('P(x0) =', y)
    print('P\'(x0) =', z)

其次,这是我最大的错误,我没有将足够的系数传递给方法

这将计算2x ^ 3

horner(-2, 2, 0, 0, 0)

我实际上不得不打电话

horner(-2, 2, 0, 0, 0, 0)