How to find derivative of a function using c

Eka picture Eka · Oct 16, 2012 · Viewed 63.5k times · Source

Is it possible to find derivative of a function using c program. I am using matlab in that it has an inbuilt function diff() which can be used for finding derivative of a function.

f(x)=x^2

Is it possible to find the derivative of above function using c. What is the algorithm for that?

Answer

user529758 picture user529758 · Oct 16, 2012

Yes, it is quite possible. However, the solution depends on your needs. If you need a simple numerical solution, the following will do (to a certain extent, with some constraints - naive implementation):

double derive(double (*f)(double), double x0)
{
    const double delta = 1.0e-6; // or similar
    double x1 = x0 - delta;
    double x2 = x0 + delta;
    double y1 = f(x1);
    double y2 = f(x2);
    return (y2 - y1) / (x2 - x1);
}

// call it as follows:
#include <math.h>

double der = derive(sin, 0.0);
printf("%lf\n", der); // should be around 1.0

For more advanced numerical calculations, you can use the GNU Scientific Library.

However, if you need to analitically find the formula of the derivative of a given function, then you have to:

  1. Parse the input formula to some abstract data type, for example an AST;
  2. Derivate it using the identities and rules of derivation (there's only a few of them, this part should be the easiest),
  3. Serialize the abstract data type you got as the result of the derivation process to a string and output that as the result.

However, you won't need to do all this; there are great C mathematical libraries that provide such functionality.

Edit: after some Googling, I couldn't find one. The closest solution for getting you started I can think of is having a look at GeoGebra's source code - although it's written in Java, it's fairly easy to read for anybody fluent enough in a C-like language. If not, just go ahead and implement that algorithm yourself :)