chapter 3.5
def f(x):
return 1 - 2 * x + 3 * x**2 - 4 * x**3
def g(x):
return 6 * x**6 - 2 * x**5 + 3*x + 5 * x**3
def h(x):
return 5 + 3 * x**2 - 2 * x**11 + x + 3 * x**15
def z(x):
return 5 + 3 * x**2 - 2 * x**11 + x + 3 * x**15-2*x**8
def p(x):
return 5 + 3 * x**2 -31 * x**10 + x + 3 * x**15+13*x**8+14*x**9
def wrong(x):
return 5 - 3 * x**2 -1 * x**10 + x + 10000000000 * x**15+13*x**8+14*x**9
def gcd(a,b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
def find_polynomial(func):
n = 15
m = (n + 1) // 2
result = [0]*(n+1)
s = [0]*(n+1)
phi = [0]*(n+1)
s[n] = m
for i in range(1, n + 1):
for j in range(n-i, n):
s[j] -= (i - m) * s[j+1]
s[n] -= (i - m)
lc = 1
for j in range(n+1):
phi[j] = n + 1
for k in range(n, 0, -1):
phi[j] = k * s[k]+(j-m)*phi[j]
lc = lcm(lc, phi[j])
for j in range(n+1):
ff = func(j-m)
mul = lc // phi[j]
b = 1
for k in range(n, -1, -1):
result[k] += b * ff * mul
b = s[k] + (j-m) * b;
for j in range(n+1):
result[j] = result[j] // lc
return result
print(find_polynomial(f))
print(find_polynomial(g))
print(find_polynomial(h))
print(find_polynomial(z))
print(find_polynomial(p))
print(find_polynomial(wrong))
[1, -2, 3, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 3, 0, 5, 0, -2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[5, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, 3]
[5, 1, 3, 0, 0, 0, 0, 0, -2, 0, 0, -2, 0, 0, 0, 3]
[5, 1, 3, 0, 0, 0, 0, 0, 13, 14, -31, 0, 0, 0, 0, 3]
[5, 1, -3, 0, 0, 0, 0, 0, 13, 14, -1, 0, 0, 0, 0, 10000000000]
def wronga(x):
return 5 - 3 * x ** 2 -77777 * x ** 100 + x + 333333333 * x ** 15+13*x ** 8+14*x ** 9
dont't forget to set proper max power:
n = 100
result:
[5, 1, -3, 0, 0, 0, 0, 0, 13, 14, 0, 0, 0, 0, 0, 333333333, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -77777]