public static class Integrator public static double Integrate Func dou

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static class Integrator
{
public static double Integrate(Func<double, double> f, double a, double b, int n = 500) //n + 1 is number of knots
{
if (n < 1) throw new Exception();
double h = (b - a) / 2 / n;
double ans1 = 0;
double ans2 = 0;
for (int i = 1; i <= 2 * n - 1; i += 2)
ans1 += f(a + h * i);
for (int i = 2; i <= 2 * n - 2; i += 2)
ans2 += f(a + h * i);
return (b - a) / 6 / n * (f(a) + 4 * ans1 + 2 * ans2 + f(b));
}
}