{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Error in finite difference approximation of derivative"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Compute derivative of\n",
"$$\n",
"f(x) = \\sin(x)\n",
"$$\n",
"at $x=2\\pi$ using finite difference\n",
"$$\n",
"\\frac{f(x+h) - f(x)}{h}\n",
"$$\n",
"for $h=10^{-1},10^{-2},\\ldots,10^{-14}$."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"from numpy import sin,arange,zeros,pi,abs\n",
"from matplotlib.pyplot import loglog,xlabel,ylabel"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def f(x):\n",
" return sin(x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"h = 10.0**arange(-1,-15,-1)\n",
"df= zeros(len(h))\n",
"x = 2.0*pi\n",
"f0= f(x)\n",
"for i in range(len(h)):\n",
" f1 = f(x+h[i])\n",
" df[i] = (f1 - f0)/h[i]\n",
"loglog(h,abs(df-1.0),'o-')\n",
"xlabel('h')\n",
"ylabel('Error in derivative');"
]
}
],
"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
}