Calculating the area under a curve programmatically

Calculating the area under a curve is a little tricky in computing languages such as c++ or c# due to there not being any direct functions to allow integration. Not wanting to write a whole intergrall solver to complete my project I opted to use an approximation method.

The method I opted for way Riemann sum, invented by a German mathematician, uses many rectangles to approximate the area:

The great thing about using the rectangle approximation is that its incredibly fast to do, as a result many iterations can be used to give a pretty accurate result.

Riemann sum in C++:
The y=x function in the example below represents a deceleration curve an object has to follow (y= Speed, x = Time). I needed to calculate the total distance traveled by the object,  as Distance = Speed * Time, the area under the curve equals the total distance traveled.

#define NUM_OF_RECTANGLESTOUSE 10 //The more rectangles used the greater the accuracy
double startX = 0; //starting position on the curve
double endX   = 1; //end position on the curve

double AreaOfCurve = 0;
double lengthX = endX - startX;
double rectangleWidth = lengthX / NUM_OF_RECTANGLESTOUSE;
for(double x=startX+(0.5*rectangleWidth); x < endX; x += rectangleWidth)
{
  //Curve function multiplied by the width goes here: (I've used y=((1/decelTime²) * (decelTime - x)²))
  AreaOfCurve +=  rectangleWidth * ((1.0/(lengthX*lengthX)) * ((lengthX - x)*(lengthX - x)));
}

A great tool to help visualize the Riemann sum and see the difference between the approximation and the actual value can be found on wolfram alpha:
Link

Other approximation methods can be used for greater accuracy, such as the trapezium rule, see WikiPedia for a full list

Leave a Reply