{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Use of polyfit and polyval"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will use polyfit and polyval from numpy to construct an approximating polynomial to the function\n",
"$$\n",
"f(x) = \\cos(4\\pi x), \\qquad x \\in [0,1]\n",
"$$\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"from numpy import linspace,cos,pi,polyfit,polyval\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define the function"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"xmin, xmax = 0.0, 1.0\n",
"f = lambda x: cos(4*pi*x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Make a grid and evaluate function at those points."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"N = 8 # degree, we need N+1 points\n",
"x = linspace(xmin, xmax, N+1)\n",
"y = f(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Construct polynomial using polyfit"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"p = polyfit(x,y,N)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we evaluate this on larger grid for better visualization"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"M = 100\n",
"xe = linspace(xmin, xmax, M)\n",
"ye = f(xe) # exact function\n",
"yp = polyval(p,xe)\n",
"\n",
"plt.plot(x,y,'o',xe,ye,'--',xe,yp,'-')\n",
"plt.legend(('Data points','Exact function','Polynomial'))\n",
"plt.title('Degree '+str(N)+' interpolation');"
]
}
],
"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": 2
}