Search code examples
cloopsfor-loopintegrationnumerical-integration

Numerical Integration, using the trapezium rule in C


I am using the trapezium rule to calculate the integral of a function between 0 and infinity. I can calculate the value of the integral for a given value of N, and now I am trying to loop N from two to a given value but it will not work. It keeps calculating the value of the integral for when N is 2 and repeating instead of the new value of N. The problem is in the for loop in main() I think.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>

double f(double x) {
 double a;
  a =1/((1+x)*pow(x,0.5));
  return a;}

double tra(double upper, double lower, int N) {
 double sum, step, integral,lowest;
  step=(upper-lower)/(N-1);
  lower=lower+step;

    if(lower==0) {
       lowest=DBL_EPSILON;}
    else {
    lowest=lower;}

    while(lower<upper) {
         sum=sum+f(lower);
         lower=lower+step;}

 integral=step*(sum+(f(upper)/2)+(f(lowest)/2));
 sum=0;
 return integral;}


main() {
int N;
double upper=DBL_EPSILON*2, lower=0, total=0;
for(N=2;N<20000;N+=100) {   /*Here im trying to loop N so that the        integral is calculated for increasing values of N*/

   while(upper<FLT_MAX) {
        total=total+tra(upper, lower, N);
        lower=upper;
        upper=upper*2;}
        printf("Integral is %.10f\n", total);
}
}

Solution

  • I suggest you move the variable initialisation to within the for loop like this:

    int main(void) {
        int N;
        double upper, lower, total;
        for(N=2;N<20000;N+=100) {
            upper = DBL_EPSILON*2;
            lower = 0;
            total = 0;
            while(upper<FLT_MAX) {
                total=total+tra(upper, lower, N);
                lower=upper;
                upper=upper*2;
            }
            printf("Integral is %.10f\n", total);
        }
        return 0;
    }