import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as pt
Let's fix the number of points and the number of functions as n
.
Make sure n
is odd.
n = 5
assert n % 2 == 1
x = np.linspace(0, 2*np.pi, n, endpoint=False)
Next, fix the values of $k$ in $\cos(kx)$ as cos_k
and in $sin(kx)$ as sin_k
so that there are exactly $n$ altogether:
cos_k = np.arange(0, n//2 + 1, dtype=np.float64)
sin_k = np.arange(1, n//2 + 1, dtype=np.float64)
print(cos_k)
print(sin_k)
Next, build the generalized Vandermonde matrix.
Make sure to order the matrix by increasing $k$:
V = np.zeros((n,n))
V[:, ::2] = np.cos(cos_k*x[:, np.newaxis])
V[:, 1::2] = np.sin(sin_k*x[:, np.newaxis])
V
Now let's try and do interpolation with this. Here are a few functions:
if 1:
def f(x):
return x
elif 0:
def f(x):
return np.abs(x-np.pi)
elif 1:
def f(x):
return (x<=np.pi).astype(np.int32).astype(np.float64)
Find the coefficients as coeffs
:
coeffs = la.solve(V, f(x))
plot_x = np.linspace(0, 2*np.pi, 1000)
interpolant = 0 * plot_x
for i, k in enumerate(cos_k):
interpolant += coeffs[2*i] * np.cos(k * plot_x)
for i, n in enumerate(sin_k):
interpolant += coeffs[2*i+1] * np.sin(n * plot_x)
pt.plot(plot_x, interpolant)
pt.plot(plot_x, f(plot_x), "--", color="gray")
pt.plot(x, f(x), "or")
abs
above?)?# Answers
#
# * Because we're interpolating with periodic functions--so the interpolant is forced to be periodic.
# * We observe a distinct "overshoot". This overshoot is called "Gibbs phenomenon".
# * Periodic: no Gibbs at interval end.
# * Gibbs can also happen in the middle of the interval.
B = V.T.dot(V)
B[np.abs(B)<1e-12] = 0
B
# Answers:
#
# * V's columns are orthogonal. (though not normalized)
# * The transpose of $V$ (with appropriate normalization) its inverse. This makes Fourier coefficients cheap to compute.
# * The normalization is n for the first entry, and n/2 for all the ones after that.
# * Computing Ax costs n**2 operations.