0

I am trying to calculate the numerical differentiation of a particular function. This function may vary (for example, can be a line or a circle).

My first thought is to define a generic function:

delegate double Function(double arg);
static double Derivative(Function f, double arg)
{
    double h = 10e-6; 
    double h2 = h*2;
    return (f(arg-h2) - 8*f(arg-h) + 8*f(arg+h) - f(arg+h2)) / (h2*6);
}

For a linear line:

double LinearLine(double arg)
{
    double m = 2.0; double c = 1.0;
    return m*arg + c;
}

I call:

Function myFunc = new Function(LinearLine);
Derivative(myFunc, 3); //Derivative at x=3

However, in this method I will need to hardcode the m and the c into the LinearLine() function.

Alternatively, if I pass m and c into the LinearLine argument list : LinearLine(double m, double c), I will have to rewrite the Derivative() function return value everytime I call a different function. (For example Circle(double radius, double x, double y)).

My question is in such a case, what would be a good way to design such a class/function?

John Tan
  • 1,331
  • 1
  • 19
  • 35
  • Side note: circle is not a function... strictly speaking... – Alexei Levenkov Feb 04 '15 at 02:27
  • This is not an analytic derivative, but a finite difference.The correct finite difference for the 1st derivative is `(f(x+h)-f(x-h))/(2*h)`. Where did you get your derivative from (reference?) – John Alexiou Feb 04 '15 at 02:28
  • Read up on differentiation of implicit functions such as `g(x,y)=0` which the circle is. https://www.math.ucdavis.edu/~kouba/CalcOneDIRECTORY/implicitdiffdirectory/ImplicitDiff.html – John Alexiou Feb 04 '15 at 02:32
  • I got the expression from a previous answer: http://stackoverflow.com/a/373265/2164904 – John Tan Feb 04 '15 at 05:09

1 Answers1

0

Note: This answer only applies to constructing functions to pass to Derivative and does not help with implicit functions (as linked by ja72)

You can define functions with lambda expressions:

  Func<float,float> myFunc = x = > 3 * x + 7;

You can also curry functions to convert n-ary function to n-1-ary one:

  float TwoArg(float x, float y) { return x * y; }
  Func<float,float> twoArg2 = x => TwoArg(x, 2);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179