As I've mentioned previously, I'm slowly reading through SICP - it's an amazing book and reading it has been a humbling experience.
I completely geeked out reading one example on functional derivatives. (Take a math expression as a parameter and return the derivative as an expression)
It's in the first chapter, and they use this to implement Newton's Method -> to then implement a Sqrt function!
After I picked my brain off the floor, I decided to have a crack at implementing derivatives in C# using lambda expressions:
Using the formula of a derivative (above), we can simply code an approximate derivative (below):
Easy huh! So for fun I decided to use linq expression trees to derive algebraically.
It's easy to get an expression tree in C# - simply use the Expression<> type.
I parse the expression tree using Matt Warren's ExpressionVisitor class - and using the basic rules of Derivation (Constant, Product and Quotient rules) we get:
Wrapping it up
To quickly finish this long blog post, here's the usage code:
And there it is! Useful? maybe not. Fun? Definitely!