{
"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": [
"