Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in a function as a function parameter [duplicate]

Tags:

c#

I am trying to implement the trapezodial rule in c# as a function:

Int_a^b f(x) = (b-a) * [f(a) + f(b)] / 2 

Is there a feature in c# which allows me to write the function as such?

double integrate(double b, double a, function f)
{
    return (b-a) * (f(a) + f(b)) / 2;
}

Where f can be any polynomial expression defined inside another function, for example:

double f (double x)
{
    return x*x + 2*x;
}
like image 785
John Tan Avatar asked Jan 09 '23 12:01

John Tan


1 Answers

In your case you want to pass a Func<double, double>. Like so

double integrate(double b, double a, Func<double, double> f)
{
    return (b-a) * (f(a) + f(b)) / 2;
}

double integrand = integrate(0, 2 * Math.PI, x => x*x + 2*x);
like image 184
Aron Avatar answered Jan 15 '23 17:01

Aron