…Being a Collection of Musings on just about anything I feel like talking about.

Sunday 21 January 2007

Differentiating Functions in C++

Myself and Das Obersturmfuhrer — henceforth known as J — were considering taking on an expression differentiator (in Lisp) recently, in his investigations J found some nice Python to do this and wondered how one might go about it in C[++]. The result of a few minutes experimentation was the following:

#include <iostream>
using namespace std;

class d
{
private:
double (*f)(double);
double h;
public:
d(double (*function)(double)) : f(function), h(0.0001) {;}
double operator()(double arg)
{
return (((*f)(arg+h)-(*f)(arg))/h);
}
};

double square(double arg)
{
return arg*arg;
}

int main()
{
cout << "square(5) = " << square(5) << endl;
cout << "d(&square)(5) = " << d(&square)(5)<< endl;
return 0;
}

If some templates were added to the functor d this would allow an open ended solution for differentiating numerical functions (albeit in a pretty crude manner); all the same I was surprised at how elegant the end result looked!

– PostScript —
Jason expounds upon the Lisp implementation:
http://jasonmc.wordpress.com/2007/01/24/fun-with-lisp/

3 comments:

tvashtar said...

Hmmm… that is an insightful point tianshangfei, but I'm not sure if I'm swayed by your argument, exactly how good is this free $5000.00 Gift Card at differentiating mathematicak functions at runtime in C[++]?

Anonymous said...

A fake trackback:
http://jasonmc.wordpress.com/2007/01/24/fun-with-lisp/

jason said...

A more informed explanation available here: http://www.cs.princeton.edu/introcs/94diffeq/