MidPoint Method implementation issues

Started by
2 comments, last by Paradigm Shifter 11 years, 4 months ago

I'm trying to implement a function that calculates the integral of a function f'(x) using the midpoint method.

Here's what I came up with:


float CMATH::midPointIntegrate(float steps,float x1, float(*F)(float x)  ){
    float stepSize = x1/steps;
    float integral = 0.0f;
    float xn = 0;
    float y0 = 0.0f;
    float ymid = 0.0f;
    float y1 = 0.0f;

    for(int I = 0; I < steps; I++){
        y0 = F(xn);
        ymid = F(xn+stepSize*0.5f);
        y1 = F(xn+stepSize);
        integral+= y0*stepSize*0.5f + (ymid - y0)*stepSize*0.25f + ymid*stepSize*0.5f + (y1-ymid)*stepSize*0.25f;
        xn+=stepSize;
    }

    return integral;
}

It appears to work, however, I was under the impression that the midpoint method requires less steps in order to calculate the integral.

Can anyone confirm that this is the correct implementation of the midpoint method because ,at the moment, i'm not really sure.

Advertisement
To my knowledge, the midpoint integration sums up rectangles with a width equal to your stepSize (assuming homogeneous sampling) and a height equal to the function value in the middle between the 2 samples. Your code snippet, however, doesn't sum up rectangles but irregular trapezoids by splitting each interval into half and fitting a trapezoid to each of them.

I'd say that

for(int I = 0; I < steps; I++) {
    ymid = F(xn+stepSize*0.5f);
    integral += ymid*stepSize;
    xn += stepSize;
}
is all what's needed for the midpoint method integration. But perhaps this is just a naming confusion!?
...But perhaps this is just a naming confusion!?

You're probably right about that.

I'm very new to numerical methods in general.

A couple of suggestions: 1) steps should be an unsigned int, not a float, and obviously you need to return an error if steps == 0
2) It's going to be more useful to provide an interval to integrate over rather than integrate from 0 to x1
3) You redundantly evaluate the beginning function value of each step after the first more than once, try calculating F(0.0f) outside of a do... while loop and use the value at F(xn+stepsize) as the next loop value of F(xn)
4) Doesn't look like it copes correctly if x1 < 0, needs to negate the answer, need to do this if you use an interval and fStart > fEnd
5) Floating point error means repeatedly adding stepsize to xn may not give you x1 as the endpoint, you should calculate it by linearly interpolating from 0 to x1 instead.

EDIT: Keep getting stupid format tags instead of newlines in my posts?
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

This topic is closed to new replies.

Advertisement