Derivatives in C/C++?

alanc10n picture alanc10n · Jan 8, 2009 · Viewed 31.8k times · Source

I have some expressions such as x^2+y^2 that I'd like to use for some math calculations. One of the things I'd like to do is to take partial derivatives of the expressions.

So if f(x,y) = x^2 + y^2 then the partial of f with respect to x would be 2x, the partial with respect to y would be 2y.

I wrote a dinky function using a finite differences method but I'm running into lots of problems with floating point precision. For example, I end up with 1.99234 instead of 2. Are there any libraries that support symbolic differentiation? Any other suggestions?

Answer

Norman Ramsey picture Norman Ramsey · Jan 8, 2009

I've implemented such libraries in several different languages, but unfortunately not C. If you are dealing only with polynomials (sums, products, variables, constants, and powers) it is pretty easy. Trig functions are also not too bad. Anything more complicated and you will probably be better off taking the time to master somebody else's library.

If you decide to roll your own, I have a few suggestions that will simplify your life:

  • Use immutable data structures (purely functional data structures) to represent expressions.

  • Use Hans Boehm's garbage collector to manage the memory for you.

  • To represent a linear sum, use a finite map (e.g., a binary search tree) to map each variable to its coefficient.

If you're willing to embed Lua into your C code and do your computations there, I have put my Lua code at http://www.cs.tufts.edu/~nr/drop/lua. One of the nicer features is that it can take a symbolic expression, differentiate it, and compile the results into Lua. You will of course find no documentation whatever :-(