Homework 0: Interpolation examples -- R. J. LeVeque

This is a demonstration of using an IPython notebook to combine code with descriptions.

It also demonstrates how to use Matlab and Chebfun from within the notebook.

Sample problem

Determine the quadratic polynomial \(p(x)\) that interpolates the data \[ (-1,3),~~(0,-1),~~(1,2) \] first using the Vandermonde matrix and then using the Lagrange form of interpolating polynomial.

To use Matlab from within the IPython notebook, first you have to install pymatbridge, see https://github.com/arokem/python-matlab-bridge.

Then the next set of commands gets Matlab running in the background (assuming it's installed on the computer you are using).

After this, any cell starting with %%matlab will be evaluated by Matlab.

In [1]:
import pymatbridge
ip = get_ipython()
pymatbridge.load_ipython_extension(ip)
Starting MATLAB on http://localhost:58730
 visit http://localhost:58730/exit.m to shut down same
.

Interpolation data for all the examples:

In [2]:
%%matlab
xj = [-1.; 0.; 1.]
yj = [3.; -1.; 2.]
xj =
    -1
     0
     1
yj =
     3
    -1
     2

Using monomials

For a quadratic interpolation we use basis functions \(1,~x,\) and \(x^2\).

Define the Vandermonde matrix: The columns are the basis functions evaluated at the interpolation points.

In [3]:
%%matlab
A = [xj.^0, xj, xj.^2]
A =
     1    -1     1
     1     0     0
     1     1     1

Solve the system for the monomial coefficients:

In [4]:
%%matlab
c = A\yj
c =
  -1.000000000000000
  -0.500000000000000
   3.500000000000000

plot the resulting polynomial on a fine grid:

In [5]:
%%matlab
x = linspace(-1, 1, 1001);
p = c(1) + c(2)*x + c(3)*x.^2;
plot(x,p)
hold on
plot(xj,yj,'.','markersize',20)

Lagrange form

Evaluate the Lagrange basis functions on the fine grid for plotting:

In [6]:
%%matlab
L1 = (x-xj(2)).*(x-xj(3)) / ((xj(1)-xj(2))*(xj(1)-xj(3)));
L2 = (x-xj(1)).*(x-xj(3)) / ((xj(2)-xj(1))*(xj(2)-xj(3)));
L3 = (x-xj(1)).*(x-xj(2)) / ((xj(3)-xj(1))*(xj(3)-xj(2)));

In this form, the data values are the coefficients

In [7]:
%%matlab
p = yj(1)*L1 + yj(2)*L2 + yj(3)*L3;

Plot this version (should look the same as before!)

In [8]:
%%matlab
clf
plot(x,p)
hold on
plot(xj,yj,'.','markersize',20)

Using Chebfun

To use Chebfun, you must download and add the location to the matlab path:

In [9]:
%%matlab
path(path,'/Users/rjl/chebfun/chebfun_v4.2.2889/chebfun')
which chebfun
/Users/rjl/chebfun/chebfun_v4.2.2889/chebfun/@chebfun/chebfun.m  % chebfun constructor

Use Chebfun to plot the function \(f(x) = \left(\frac{1}{1 + 25x^2}\right)^{10}\) and the function \(g(x) = 5 \int_0^x f(s)\, ds.\)

What degree polynomial approximation is used for each?

In [10]:
%%matlab
x = chebfun('x');
f = (1./(1+25*x.^2)).^10;
g = 5*cumsum(f);
clf
plot(f,'b')
hold on
plot(g,'r')
legend('f','g')

disp(sprintf('The degree of f is %i', length(f)-1))
disp(sprintf('The degree of g is %i', length(g)-1))
The degree of f is 272
The degree of g is 215

In [10]: