How to find derivative of a function using c

There is nothing built into the C language to enable this. You might be able to find a numerical library to do it though if you search online, although I would doubt that there is anything available that will provide symbolic derivatives. You could consider coding approximate numerical derivatives yourself using forward, backward and/or central differences.


For simple functions the following numerical differentiation works quite well:

typedef double (*TFunc)(double);

// general approximation of derivative using central difference
double diff(TFunc f, double x, double dx=1e-10)
{
  double dy = f(x+dx)-f(x-dx);
  return dy/(2.*dx);
}

// more or less arbitrary function from double to double:
double f(double x)
{
   return x*x;
}

// and here is how you get the derivative of f at specified location
double fp = diff(f, 5.);

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 :)

Tags:

C

Derivative