Complex-Step Differentiation

A simple way to do a numerical approximations for first derivatives is illustrated by the following:

In[10]:= exact = Cos[1];

In[13]:= nd[expr_, var_, val_] := 
 10^8 Im[(expr /. var -> val + I 1. 10^-8) ]

In[14]:= nd[Sin[x], x, 1]

Out[14]= 0.540302

In[15]:= % - exact

Out[15]= 0.
2 Likes

This is pretty neat! Here’s why it works if anyone is interested:

Im[z] == (z - Conjugate[z])/(2I)

and thus

Im[f[x + h*I]]/h == (f[x + h*I] - f[x - h*I])/(2h*I)

which is the central difference quotient.

(This only works if we assume x and h are real and f is analytic at x.)

1 Like

A paper on it by Martins, Sturdza and Alonso can be found with a Google search.

1 Like