I absolutely love lambda expressions in C#. I finally got around to trying to write a good derivation function, and produced this piece:
/// <summary>
/// Derives f(x)
/// </summary>
/// <param name="f">The function f(x) to be derived</param>
/// <returns>The derivative df/dx as a function</returns>
public static Func<double, double> fprime(Func<double, double> f)
{
return x =>
{
double h = 1;
double tempf = 0;
double guessf = 0;
do
{
tempf = guessf;
guessf = (f(x + h) - f(x)) / h;
h = h / 10;
} while (Math.Abs((guessf - tempf) / guessf) > 0.001);
return guessf;
};
}
