# Complex variable method for approximation of derivative¶

Compute derivative of $$f(x) = \sin(x)$$ at $x=2\pi$ using the complex variable method $$\frac{\textrm{imag } f(x+ih)}{h}$$ for $h=10^{-1},10^{-2},\ldots,10^{-14}$.

In [1]:
from numpy import sin,arange,zeros,pi,abs,imag
from matplotlib.pyplot import loglog,xlabel,ylabel

In [2]:
def f(x):
return sin(x)

In [3]:
h = 10.0**arange(-1,-15,-1)
df= zeros(len(h))
x = 2.0*pi
for i in range(len(h)):
df[i] = imag(f(x+1j*h[i]))/h[i]
loglog(h,abs(df-1.0),'o-')
xlabel('h')
ylabel('Error in derivative')
print df-1.0

[  1.66750020e-03   1.66667500e-05   1.66666675e-07   1.66666658e-09
1.66666680e-11   1.66755498e-13   1.77635684e-15   0.00000000e+00
0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
0.00000000e+00   0.00000000e+00]


Once $h$ is below $10^{-7}$ the error in the derivative approximation is zero. The formula is second order accurate $$\frac{\textrm{imag } f(x+ih)}{h} = f'(x) + O(h^2)$$