{
"metadata": {
"name": "",
"signature": "sha256:17921cd7d4a1f5fb3c22143f158084835312121c6996f05564df87d27907b18b"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"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",
"collapsed": false,
"input": [
"from numpy import sin,arange,zeros,pi,abs,imag\n",
"from matplotlib.pyplot import loglog,xlabel,ylabel"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def f(x):\n",
" return sin(x)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"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"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[ 1.66750020e-03 1.66667500e-05 1.66666675e-07 1.66666658e-09\n",
" 1.66666680e-11 1.66755498e-13 1.77635684e-15 0.00000000e+00\n",
" 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n",
" 0.00000000e+00 0.00000000e+00]\n"
]
},
{
"metadata": {},
"output_type": "display_data",
"svg": [
"\n",
"\n",
"\n",
"\n"
],
"text": [
""
]
}
],
"prompt_number": 3
},
{
"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": {}
}
]
}