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?

  • 2
    $\begingroup$ Hi. Have a look at the material at: dsprelated.com/showarticle/35.php $\endgroup$ Feb 14, 2020 at 12:27
  • $\begingroup$ @RichardLyons cool stuff- thanks! I am favoriting this one to find my way back to your blog post on it. $\endgroup$ Feb 19, 2020 at 22:31

2 Answers 2


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} $$

which does not amplify high-frequency noise.


In a 2003 paper in French, "Estimation par maximum de vraisemblance de la dérivée d’un signal bruité. Application à la caractérisation de vérins pneumatiques" (Maximum likelihood estimation of the derivative of a noisy signal. Application to the characterization of pneumatic cylinders) [from the early GRETSI french-speaking conference on signal and image processing], there are higher-lag formulae, allowing recursive estimators based on maximum likelihood, with hypotheses on signal behavior: constant speed, constant acceleration, constant jerk. You can find higher-lag derivatives (possibly better in noise handling), like:

$$\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)$$

I hope they can suit some needs. French may be an issue, but formulae are self contained.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.