Numerical Integration, using the trapezium rule in C

会有一股神秘感。 提交于 2020-01-06 06:56:10

问题


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);
}
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/29018299/numerical-integration-using-the-trapezium-rule-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!