快速多项式移位

时间:2018-07-05 19:26:10

标签: python algorithm math polynomials taylor-series

我正在尝试实现“ F.卷积方法”(第2.2节):

enter image description here

来自Fast algorithms for Taylor shifts and certain difference equations(在底部或here):

from math import factorial

def convolve(f, h):
    g = [0] * (len(f) + len(h) - 1)
    for hindex, hval in enumerate(h):
        for findex, fval in enumerate(f):
            g[hindex + findex] += fval * hval
    return g

def shift(f, a):
    n = len(f) - 1
    u = [factorial(i)*c for i, c in enumerate(f)]
    v = [factorial(n)*a**i//factorial(n-i) for i in range(n + 1)]
    g = convolve(u, v)
    g = [c//(factorial(n)*factorial(i)) for i, c in enumerate(g)]
    return g

f = [1, 2, 3, -4, 5, 6, -7, 8, 9]
print(shift(f, 1))

但是我只有零,而正确的结果应该是:

[1, 10, 45, 112, 170, 172, 116, 52, 23]

请,有人知道我在做什么错吗?

2 个答案:

答案 0 :(得分:3)

我仍然没有完全掌握算法,但是您遇到了一些错误:

  1. u的幂始于n,结束于0。为了使卷积正常工作,您需要将其反转,因为您期望卷积函数中的系数是有序的。
  2. v多项式中的系数仅取决于j,而不取决于n-j(您使用i
  3. 仅需要卷积的前n+1个元素(您不需要n+1 ... 2n的幂。
  4. 所得到的卷积(实际上不是卷积吗?)是“向后的”,因为在您中,最终结果将从i=0开始计算,因此x**(n-i=n)的功效就可以了。

将所有这些放在一起:

from math import factorial

def convolve(f, h):
    g = [0] * (len(f) + len(h) - 1)
    for hindex, hval in enumerate(h):
        for findex, fval in enumerate(f):
            g[hindex + findex] += fval * hval
    return g

def shift(f, a):
    n = len(f) - 1
    u = [factorial(i)*c for i, c in enumerate(f)][::-1]
    v = [factorial(n)*a**i//factorial(i) for i in range(n + 1)]
    g = convolve(u, v)
    g = [g[n-i]//(factorial(n)*factorial(i)) for i in range(n+1)][::-1]
    return g

f = [1, 2, 3, -4, 5, 6, -7, 8, 9]
print(shift(f, 1))

我明白了

[9, 80, 301, 636, 840, 720, 396, 132, 23]

我不知道为什么这与您的期望不同,但是我希望这能使您步入正轨。

答案 1 :(得分:1)

自从您要求我的实现(这些操作有f个“后退”):

等式2:

from math import factorial
from collections import defaultdict

def binomial(n, k):
    try:
        binom = factorial(n) // factorial(k) // factorial(n - k)
    except ValueError:
        binom = 0
    return binom

f = [1, 2, 3, -4, 5, 6, -7, 8, 9][::-1]
k=0
n = len(f) - 1

g = defaultdict(int)
for k in range(n+1):
    for i in range(k, n+1):
        g[i-k] += binomial(i,k) * f[i]

print(g)
# defaultdict(<class 'int'>, {0: 23, 1: 52, 2: 116, 3: 172, 4: 170, 5: 112, 6: 45, 7: 10, 8: 1})

2.2(F)中的方程:

from math import factorial
from collections import defaultdict

def convolve(x, y):
    g = defaultdict(int)
    for (xi, xv) in x.items():
        for (yi, yv) in y.items():
            g[xi + yi] += xv * yv
    return g


def shift(f, a):
    n = len(f) - 1
    u = {n-i: factorial(i)*c for (i, c) in enumerate(f)}
    v = {j: factorial(n)*a**j//factorial(j) for j in range(n + 1)}
    uv = convolve(u, v)

    def g(k):
        ngk = uv[n-k]
        return ngk // factorial(n) // factorial(k)

    G = [g(k) for k in range(n+1)]
    return G

f = [1, 2, 3, -4, 5, 6, -7, 8, 9]

print(shift(f, 1))
# [23, 132, 396, 720, 840, 636, 301, 80, 9]