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) \] 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.
import pymatbridge
ip = get_ipython()
pymatbridge.load_ipython_extension(ip)
%%matlab
xj = [-1.; 0.; 1.]
yj = [3.; -1.; 2.]
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.
%%matlab
A = [xj.^0, xj, xj.^2]
Solve the system for the monomial coefficients:
%%matlab
c = A\yj
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:
%%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
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?
%%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))