# MidPoint Method implementation issues

This topic is 2154 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
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!? Edited by haegarr

##### Share on other sites
...But perhaps this is just a naming confusion!?

I'm very new to numerical methods in general.

##### Share on other sites
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?

1. 1
Rutin
73
2. 2
3. 3
4. 4
5. 5

• 21
• 10
• 33
• 20
• 9
• ### Forum Statistics

• Total Topics
633424
• Total Posts
3011806
• ### Who's Online (See full list)

There are no registered users currently online

×