In [2]:
import numpy as np
import matplotlib.pyplot as plt

def f(x):   return np.sin(3*x)*np.log(x)

In [3]:
x = 0.7
h_exp = range( 1, 30 )
hs = map( lambda p: 10 ** -p, h_exp )
h_len = len(hs)

In [4]:
dfdx_analytical = np.ones( h_len ) * 3 * np.cos( 3*x)*np.log(x) + np.sin(3*x) / x
dfdx_finite_diff = map( lambda h: (f(x + h) - f(x))/h, hs )
dfdx_central_diff = map( lambda h: (f(x+h)-f(x-h))/(2*h), hs )
dfdx_complex_step = map( lambda h: np.imag(f(x + np.complex(0, h))/h), hs )

In [21]:
fig, axes = plt.subplots(figsize=(12,10))
axes.set_title('calculated derivative as a function of N, where the step size is 10 ** -N')
axes.set_xlabel('N')
axes.set_ylabel('derivative')
axes.plot(h_exp, dfdx_analytical, color="blue", linestyle="steps", linewidth=2.00, label="analytical")
axes.plot(h_exp, dfdx_finite_diff, color="grey", linestyle='-', linewidth=2.00, marker='+',label="finite diff")
axes.plot(h_exp, dfdx_central_diff, color="green", linestyle='-.', label="central diff")
axes.plot(h_exp, dfdx_complex_step, color="red", linestyle=":", marker='+',label="complex step")
axes.legend(loc=3)
axes.set_ylim([1.7, 1.8])


Out[21]:
(1.7, 1.8)

In [23]:
fig, axes = plt.subplots(figsize=(12,10))
axes.set_title('calculated derivative as a function of N, where the step size is 10 ** -N')
axes.set_xlabel('N')
axes.set_ylabel('derivative')
axes.plot(h_exp, dfdx_analytical, color="blue", linestyle="steps", linewidth=2.00, label="analytical")
axes.plot(h_exp, dfdx_complex_step, color="red", linestyle=":", marker='+',label="complex step")
axes.legend(loc=3)
axes.set_ylim([1.77, 1.78])


Out[23]:
(1.77, 1.78)