{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Interpolate $\\cos(x)$ on uniform points"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us interpolate $\\cos(x)$ on uniformly spaced points in the interval $[0,2\\pi]$."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"from numpy import pi,cos,linspace,polyfit,polyval\n",
"from matplotlib.pyplot import figure,subplot,plot,axis,text"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"xmin, xmax = 0.0, 2.0*pi\n",
"fun = lambda x: cos(x)\n",
"\n",
"xx = linspace(xmin,xmax,100);\n",
"ye = fun(xx);\n",
"\n",
"figure(figsize=(9,8))\n",
"for i in range(1,7):\n",
" N = 2*i;\n",
" subplot(3,2,i)\n",
" x = linspace(xmin,xmax,N+1);\n",
" y = fun(x);\n",
" P = polyfit(x,y,N);\n",
" yy = polyval(P,xx);\n",
" plot(x,y,'o',xx,ye,'--',xx,yy);\n",
" axis([xmin, xmax, -1.1, +1.1])\n",
" text(3.0,0.0,'N='+str(N))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The interpolating polynomials converge to the true function as $N$ increases.\n",
"\n",
"Also try the above program for $\\cos(2x)$."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 1
}