Can I possibly do a program in C++ to compute for the integral of a given function?

It must also compute for its definite integral based from its given limits. Help please.

How should I make the program? What C++ Library shall I include? Thanks!

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    You can but you would have to write all of the code yourself. You need to include the math lib but that's about it.

    Using some online calculator like (see below) is easier if you just need it to check your answers

    http://www.quickmath.com/webMathematica3/quickmath...

    If you do decide to code your own calculator:

    Here is some source I found for finding definite integrals using the trapezoidal method:

    // Returns the area of a trapezoid of a given height where sideA

    // and sideB are the uneven sides

    float CalculateTrapezoidArea(float sideA, float sideB, float height)

    {

    // Area of a trapezoid: A = (a+b)h / 2 (Wikipedia)

    return ( ( (sideA+sideB) * height ) / 2.0f );

    }

    // Approximates the area under the curve of function pointed to by pFunc

    // (which must take and return a float) in the range x=start to x=end.

    // Accuracy is determined by number of steps used between these values.

    float ApproximateIntegral(float (*pFunc)(float), float start, float end, unsigned steps)

    {

    // pFunc is a pointer to a function that takes and returns a float, which we will use as f(x).

    // The general method is to calculate points at step intervals and calculate area of

    // the trapezoid underneath then add areas together

    int i;// counter

    float diff; // the difference between steps - used as trapezoid height later

    float* xValues = new float[steps + 2]; // start, end and steps in between

    float* yValues = new float[steps + 2]; // for calculated results

    // set start and end x values

    xValues[0] = start;

    xValues[steps + 1] = end;

    // Interpolate x values for number of steps

    // Loop from second element to penultimate element

    diff = (end - start) / (steps + 1);

    for (i = 1; i <= steps; ++i)

    {

    xValues[i] = xValues[i - 1] + diff;

    }

    // now we have all the x values, calculate all corresponding y values (or f(x))

    for (i = 0; i < steps + 2; ++i)

    {

    yValues[i] = (*pFunc)(xValues[i]);

    }

    // now calculate the area under each trapezoid

    // a will be first y of pair, b will be second y, h will be diff from earlier

    float finalArea = 0.0f;

    // we always need to do n-1 traps where n is the number of points we have

    for (i = 0; i < steps + 1; ++i)

    {

    finalArea += CalculateTrapezoidArea(yValues[i], yValues[i+1], diff);

    }

    delete[] xValues;

    delete[] yValues;

    return finalArea;

    }

Still have questions? Get your answers by asking now.