public double Integral(double[] x, double intPointOne, double intPointTwo)
{
double integral = 0;
double i = intPointOne;
do
{
integral += Function(x[i])*.001;
i = i + .001;
}
while (i <= intPointTwo);
return integral;
}
Here's a function I have to integrate a function from x1-x2 simply using a summation of parts. How can I make this loop more efficient (using less loops), but more accurate?
Where Function
changes every iteration, but it should be irrelevant as it's order of magnitude (or boundary) should stay relatively the same...
1) look into section 4.3 of http://apps.nrbook.com/c/index.html for a different algorithm.
2) To control the accuracy/speed factor you may need to specify the bounds
x_low
andx_high
as well as how many slices you want in the integral. So your function would look like thisOnce you understand this basic integration, you can move on to more elaborate schemes mentioned in Numerical Recipies and other sources.
To use this code issue a command like
A = Integrate( Math.Sin, 0, Math.PI, 1440 );
If you know functions in advance than you can analyze them and see what integration steps size works for your purposes. I.e. for linear function you need just one step, but for other functions you may need variable steps. At least see if you can get away with something like
(pointTwo - pointOne)/1000.0
.If you need it for generic function and it is not homework you should strongly consider existing libraries or refreshing on your first-second year math courses...
Note your code actually have bug of not using i (which is very bad name for x):
You are using the left-hand rule for integrating. This is only semi-accurate as long as the function has a positive and negative slope across the domain (since the errors of using the left end point cancel out).
I would recommend, at least, moving to the trapezoidal rule (calculate the area under the trapezoid formed by the set (x[i], 0), (x[i+0.001], 0), (x[i], Function(x[i]), (x[i+0.001], Function(x[x+0.001]).
An even better solution is to use Simpson's rule. It is a slower algorithm, but the accuracy should allow you to significantly increase your interval.
Look here: Numerical Integration for details.
Here the calculation of the integral through methods: left hand, trapezoidal and mid point