{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Complex variable method for approximation of derivative"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Compute derivative of\n",
"$$\n",
"f(x) = \\sin(x)\n",
"$$\n",
"at $x=2\\pi$ using the complex variable method\n",
"$$\n",
"\\frac{\\textrm{imag } f(x+ih)}{h}\n",
"$$\n",
"for $h=10^{-1},10^{-2},\\ldots,10^{-14}$."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"from numpy import sin,arange,zeros,pi,abs,imag\n",
"from matplotlib.pyplot import loglog,xlabel,ylabel"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"def f(x):\n",
" return sin(x)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1.66750020e-03 1.66667500e-05 1.66666675e-07 1.66666658e-09\n",
" 1.66666680e-11 1.66755498e-13 1.55431223e-15 2.22044605e-16\n",
" 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n",
" 0.00000000e+00 0.00000000e+00]\n"
]
},
{
"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",
"for i in range(len(h)):\n",
" df[i] = imag(f(x+1j*h[i]))/h[i]\n",
"loglog(h,abs(df-1.0),'o-')\n",
"xlabel('h')\n",
"ylabel('Error in derivative')\n",
"print(df-1.0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once $h$ is below $10^{-7}$ the error in the derivative approximation is zero. The formula is second order accurate\n",
"$$\n",
"\\frac{\\textrm{imag } f(x+ih)}{h} = f'(x) + O(h^2)\n",
"$$"
]
}
],
"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
}