Skip to content

Instantly share code, notes, and snippets.

@normalhuman
Created September 19, 2015 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save normalhuman/1f7c897c33c87a0f95ef to your computer and use it in GitHub Desktop.
Save normalhuman/1f7c897c33c87a0f95ef to your computer and use it in GitHub Desktop.
Plots the Newton polynomial interpolating a given function (and shows the Runge phenomenon)
function plot_newton
f = @(x) 1./(1+x.^2); % function to interpolate
x = -5:5; % nodes of interpolation
y = f(x);
c = coeff(x,y); % calculate Newton polynomial coefficients
t = linspace(-5,5);
poly = newton(c,x,t); % evaluate the polynomial
plot(t,[f(t);poly]); % plot function and its polynomial
hold on
plot(x,y,'ro') % also mark the interpolated values
end
function c = coeff(x,y)
n = length(x);
for k = 2:n
y(k:n) = (y(k:n)-y(k-1))./(x(k:n)-x(k-1));
end
c = y;
end
function p = newton(c,x,t)
n = length(x);
p = c(n)*ones(size(t));
for k = n-1:-1:1
p = (t-x(k)).*p + c(k);
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment