# Real time numerical differentiation of signals

I am trying to implement a PID controller in Python and I am having some problems with real time numerical differentiation of my my discrete signal.

I am using the following method:

$$d{\frac{x_n}{t}} = \frac{x_{n-1}-x_n}{d_t}$$

Where $$d_t$$ is the time difference of the measurement time of $$x_n$$ and $$x_{n-1}$$.

The differentiation is accurate to some point but the results on real time systems are not as accurate as I would like to be. The differential controller does not really improve the stability of the system in most cases. At high gains it starts introducing noise into the system.

Most numerical differentiation methods recommend going into the future ($$x _{n+1}$$) and sadly for my system that's not possible. Such as:

$$\frac{x_{n+1}-x_{n-1}}{2\times d_t}$$

Are there any methods for calculating real-time differentiation with better accuracy?

• Hi. Have a look at the material at: dsprelated.com/showarticle/35.php – Richard Lyons Feb 14 '20 at 12:27
• @RichardLyons cool stuff- thanks! I am favoriting this one to find my way back to your blog post on it. – Dan Boschen Feb 19 '20 at 22:31

Your original differentiator, which should be $$x(n)-x(n-1)$$, is called a "first difference" differentiator. That differentiator amplifies high-frequency noise. As a next step I suggest you try what's called the "central difference" differentiator defined by:
$$\mathit{Diff} = \frac{x(n)-x(n-2)}{2}$$
$$\frac{1}{2} \left(3 x[k] - 4 x[k - 1] + x[k - 2]\right)$$ or $$\frac{1}{30} \left(10 x[k] - x[k - 1] -2 x[k - 2]-3 x[k - 3]-4 x[k - 4]\right)$$