take the integral of a function in csharp

Here's an example C# code to calculate the integral of a function using the trapezoidal rule:

main.cs
public static double Integrate(Func<double, double> f, double a, double b, int n)
{
    double h = (b - a) / n;
    double sum = (f(a) + f(b)) / 2.0;
    for (int i = 1; i < n; i++)
    {
        double x = a + i * h;
        sum += f(x);
    }
    return sum * h;
}
267 chars
12 lines

You can pass a function delegate f that represents the function to integrate, and specify the limits a and b of the integral and the number of intervals n to use for the trapezoidal rule. The function returns the approximate value of the integral of f over the interval [a, b].

gistlibby LogSnag