% ask matlab to plot interpolating poly of degree n % on [-1,1] for function function f % need n+1 interp points function poly2(n) set(0,'defaultlinelinewidth',3); set(0,'defaulttextfontsize',16); set(0,'defaultaxesfontsize',16); % First use equally spaced points dx = 2/n; x = -1:dx:1; % x are the interpolation points assert(length(x) == n+1); % not sure how roundoff handled y = f(x); % get data to iterpolate hold off h1 = plot(x,y,'b+'); % plot data points to make sure ok pause % ask matlab finds the poly: p = poly coeffs p = polyfit(x,y,n); % evaluate poly for plotting t=-1:.025:1; % same interval as interp points but many more z=polyval(p,t); % ask matlab to evaluate hold on plot(t,z,'r') pause % Second: use Chebyshev points for interpolation npoints = linspace(0,n,n+1); xcheb = cos(pi*npoints/n); % alternate def is cos((2i+1)/2(n+1) * pi) ycheb = f(xcheb); h2 = plot(xcheb,ycheb,'g*'); pause pcheb = polyfit(xcheb,ycheb,n); zcheb = polyval(pcheb ,t); plot(t,zcheb,'m'); legend([h1 h2],'equally spaced','chebyshev') % what is error: exactf = f(t); err_equal = abs(exactf - z); err_cheb = abs(exactf - zcheb); outline = sprintf(' for degree %3d max errors are: %15.7e %15.7e',n,max(err_equal),max(err_cheb)); disp(outline); end % ============================================================= % illustrate Runge phenomena using standard function f function y = f(x) y = 1./(1+25*x.*x); end