h1

Differentiating Functions in C++

January 21, 2007

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/

Advertisements

5 comments

  1. hey, I just got a free $5000.00 Gift Card. you can redeem yours at Abercrombie Fitch All you have to do to get yours is Click Here to get a $5000 free gift card for your backtoschool wardrobe


  2. 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[++]?


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


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


  5. I’d like to point out that thid method should be used with care. There’s a sweet spot somewhere for choosing ‘h’. If ‘h’ is too large the discretization error will dominate the error. If ‘h’ is too small the loss of significance will dominate the error.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: