Skip to content

Instantly share code, notes, and snippets.

@IshitaTakeshi
Last active June 29, 2017 00:57
Show Gist options
  • Save IshitaTakeshi/0b61621cec6a68ded3a5799759de8bfe to your computer and use it in GitHub Desktop.
Save IshitaTakeshi/0b61621cec6a68ded3a5799759de8bfe to your computer and use it in GitHub Desktop.
Lagrange Interpolation
using PyPlot
using PyCall
function generate_Lᵢ(xs, ys, i)
function Lᵢ(x)
n, d = 1, 1
for (j, xⱼ) in enumerate(xs)
if i == j
continue
end
n *= (x-xⱼ)
d *= (xs[i]-xⱼ)
end
return n / d
end
return Lᵢ
end
function generate_pₙ(xs, ys)
function pₙ(x)
v = 0
for (i, y) in enumerate(ys)
Lᵢ = generate_Lᵢ(xs, ys, i)
v += Lᵢ(x) * y
end
return v
end
return pₙ
end
xs = 0.5:0.5:2.5
ys = [
0.479425539,
0.841470985,
0.997494987,
0.909297427,
0.598472144
]
pₙ = generate_pₙ(xs, ys)
xs = collect(0.0:0.1:3.0)
fig, ax = subplots()
ax[:plot](xs, [pₙ(x) for x in xs], label=L"$p_n(x)$")
ax[:plot](xs, [sin(x) for x in xs], label=L"$sin(x)$")
ax[:legend](loc="lower center")
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment