Developed by Randy LeVeque for a course on Approximation Theory and Spectral Methods at the University of Washington.
See http://faculty.washington.edu/rjl/classes/am590a2013/codes.html for more IPython Notebook examples.
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.
Determine the quadratic polynomial p(x) that interpolates the data (−1,3), (0,−1), (1,2)
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.
import pymatbridge
ip = get_ipython()
pymatbridge.load_ipython_extension(ip)
Starting MATLAB on http://localhost:54956 visit http://localhost:54956/exit.m to shut down same ...MATLAB started and connected!
%%matlab
xj = [-1.; 0.; 1.]
yj = [3.; -1.; 2.]
xj = -1 0 1 yj = 3 -1 2
For a quadratic interpolation we use basis functions 1, x, and x2.
Define the Vandermonde matrix: The columns are the basis functions evaluated at the interpolation points.
%%matlab
A = [xj.^0, xj, xj.^2]
A = 1 -1 1 1 0 0 1 1 1
Solve the system for the monomial coefficients:
%%matlab
c = A\yj
c = -1.000000000000000 -0.500000000000000 3.500000000000000
plot the resulting polynomial on a fine grid:
%%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)
Evaluate the Lagrange basis functions on the fine grid for plotting:
L1(x)=(x−x2)(x−x3)(x1−x2)(x1−x3),L2(x)=(x−x1)(x−x3)(x2−x1)(x2−x3),L3(x)=(x−x1)(x−x2)(x3−x1)(x3−x2)%%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
%%matlab
p = yj(1)*L1 + yj(2)*L2 + yj(3)*L3;
Plot this version (should look the same as before!)
%%matlab
clf
plot(x,p)
hold on
plot(xj,yj,'.','markersize',20)
To use Chebfun, you must download and add the location to the matlab path:
%%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)=(11+25x2)10 and the function g(x)=5∫x0f(s)ds.
What degree polynomial approximation is used for each?
%%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