We will use polyfit and polyval from numpy to construct an approximating polynomial to the function $$ f(x) = \cos(4\pi x), \qquad x \in [0,1] $$ Not that polyfit actually performs a least squares fit, but we give $N+1$ points and ask for a degree $N$ polynomial, which gives an interpolating polynomial.
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
from numpy import linspace,cos,pi,polyfit,polyval
import matplotlib.pyplot as plt
Define the function
xmin, xmax = 0.0, 1.0
f = lambda x: cos(4*pi*x)
Make a grid and evaluate function at those points.
N = 8 # degree, we need N+1 points
x = linspace(xmin, xmax, N+1)
y = f(x)
Construct polynomial using polyfit
p = polyfit(x,y,N)
Now we evaluate this on larger grid for better visualization
M = 100
xe = linspace(xmin, xmax, M)
ye = f(xe) # exact function
yp = polyval(p,xe)
plt.plot(x,y,'o',xe,ye,'--',xe,yp,'-')
plt.legend(('Data points','Exact function','Polynomial'))
plt.title('Degree '+str(N)+' interpolation');