Domanda

I'm totally stuck with that, i don't know where to start.

I have to Integrate a function between a and b with n intervals in C.

I only have the function definition :

float funcintegrate(float (*f)(float x), float a, float b, int n);

I need to use the trapezoidal method.

EDIT :

Thanks all for you tips. I have now the answer !

Numerically integrate the function in the interval [a, b] using trapezoidal method (or rule) :

float funcintegrate(float (*f)(float x), float a, float b, int n);

int i;
double x;
double k = (b - a) / n;
double s = 0.5 * (f(a) + f(b));

    for (i = 1; i < n; i++) {
         x = a + k * i;
         s = s + f(x);
    }

return s * k;

}
È stato utile?

Soluzione

Your funcintegrate() function should basically divide the [a, b] interval into n subintervals, calculate the value of f() on all subinterval endpoints, then use them to compute a value of certain expression for each of the subintervals and finally add up all the values of that expression.

The subexpression to calculate in each iteration depends on the particular numerical integration method you have chosen and impacts performance and accuracy trade-off.

In the simplest case the expression is the product of the value of f() at one of the endpoints multiplied by the length of the subinterval. This corresponds to "bar-chart approximation" to the field under the curve. It is very inaccurate and once you successfully implement it you should try more complex methods.

These two wikipedia articles give a good description of a number of different methods each sharing the general algorithm I described above: Euler method, Runge-Kutta methods.

I also recommend reading relevant chapters in "Numerical Recipes in C".

EDIT: Trapezoidal method uses for each subinterval an expression which represents the area of a trapezoid which is based on the subinterval and extends upwards (or downwards depending on the sign of f()) until its vertical sides cross the curve. The two intersection points are their connected with a straight line (which is where approximation is made since f() may not be straight between the points).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top