Passing a function as a function parameter

I am trying to implement a trapezoid rule in C # as a function:

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

Is there a function in C # that allows me to write a function as such?

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

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

double f (double x)
{
    return x*x + 2*x;
}
+4
source share
2 answers

In your case, you want to pass Func<double, double>. In this way

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);
+7
source

You can do this with a type type Func<>where the first family tree represents the passed type and the second represents the return type of the function:

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

Your call will look like this:

var a = 1.0;
var b = 2.0;

var result = integrate(b, a, f);

Or, if you prefer the lambda expression:

var result = integrate(b, a, x => x*x + 2*x);
+2
source

Source: https://habr.com/ru/post/1584827/


All Articles