Interpolation
Copyright By PowCoder代写 加微信 powcoder
using LinearAlgebra, Plots
# Evenly spaced points
# Monomial basis
# Conclusion: it may diverge (and its unstable)
f = x -> 1/(25x^2 + 1) # Runge’s function
𝐱 = range(-1,1; length=n)
V = 𝐱 .^ (0:n-1)’ # Vandermonde matrix
𝐟 = f.(𝐱) # sample of a function
c = V \ 𝐟 # coefficients
p = x -> dot(c, x .^ (0:n-1)) # polynomial
g = range(-1,1; length=10_000)
plot(g, f.(g); label=”f”)
plot!(g, p.(g); label=”p”)
scatter!(𝐱, 𝐟; label=nothing)
function lagrangebasis(𝐱, k, x)
n = length(𝐱)
for j = 1:n
ret *= (x-𝐱[j])/(𝐱[k]-𝐱[j])
function lagrangeinterpolation(𝐱, 𝐟, x)
n = length(𝐱)
for k = 1:n
ret += 𝐟[k]*lagrangebasis(𝐱, k, x)
lagrangeinterpolation (generic function with 1 method)
# Evenly spaced points
# Lagrange basis
# Conclusion: it may diverge (and its unstable)
f = x -> 1/(25x^2+1)
𝐱 = range(-1,1; length=n)
p = x -> lagrangeinterpolation(𝐱, 𝐟, x)
g = range(-1,1; length=10_000)
plot(g, f.(g); label=”f”)
plot!(g, p.(g); label=”p”)
scatter!(𝐱, 𝐟; label=nothing)
# Roots of T_n(x)
# Monomial basis
# Converges! (but some instable)
f = x -> 1/(25x^2+1) # Runge’s function
T(k,x) = cos(k*acos(x))
# roots of T(n,x) = cos(n*acos(x))
𝐱 = cos.(π/n*[j-1/2 for j=1:n])
V = 𝐱 .^ (0:n-1)’ # Vandermonde
p = x -> dot(c, x .^ (0:n-1))
g = range(-1,1; length=10_000)
plot(g, f.(g); label=”f”)
plot!(g, p.(g); label=”p”)
scatter!(𝐱, 𝐟; label=nothing)
norm(T.(n,𝐱))
1.530709406528767e-11
# Roots of orthogonal polynomials T_n(x)
# Basis of OPs [T_0(x),…,T_{n-1}(x)]
# Converges! And it is stable!
# OPs WIN!!
f = x -> 1/(25x^2+1)
𝐱 = cos.(π/n*[j-1/2 for j=1:n])
T(k,x) = cos(k*acos(x))
V = T.((0:n-1)’, 𝐱)
p = x -> dot(c, cos.((0:n-1) * acos(x)))
g = range(-1,1; length=10_000)
plot(g, f.(g); label=”f”)
plot!(g, p.(g); label=”p”)
scatter!(𝐱, 𝐟; label=nothing)
norm(abs.(f.(g) – p.(g))) # polynomial matches f to roughly machine precision
4.4601288499505244e-14
plot(g, abs.(f.(g) – p.(g)); label=”f”)
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com