数值积分,使用C中的梯形规则 [英] Numerical Integration, using the trapezium rule in C

查看:193
本文介绍了数值积分,使用C中的梯形规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的梯形规则来计算0和无穷大之间的函数的积分。我可以计算积分的价值为N的给定值,现在我想循环n从两个给定值,但它不会工作。它使计算的积分为当N的值是2,而是重复N的新值的问题是在对于在主()我认为循环的

 的#include<&stdio.h中GT;
#包括LT&;&math.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&FLOAT.H GT;双F(双X){
 双A;
  一个= 1 /((1 + X)* POW(X,0.5));
  返回;}双TRA(双高,双低,INT N){
 双和,一步,积分,最低的;
  步骤=(上部低级)/(N-1);
  低=低+一步;    如果(低级== 0){
       最低= DBL_EPSILON;}
    其他{
    最低=低;}    而(下部密封环上){
         总和=总和+ F(低级);
         低=低+步;} 积分=步骤*(总和+(F(上部)/ 2)+(F(最低)/ 2));
 总和= 0;
 回到积分;}
主(){
INT N;
双上部= DBL_EPSILON * 2,低级= 0,总= 0;
为(N = 2; N< 20000; N + = 100){/ *在这里,这样的积分计算增加N *值我尝试循环N /   而(上< FLT_MAX){
        总=总+ TRA(上,下,N);
        低=上;
        上=上* 2;}
        的printf(整体是%.10f \\ n,总数);
}
}


解决方案

我建议你移动变量初始化到循环中是这样的:

  INT主要(无效){
    INT N;
    双上部,下部,总;
    为(N = 2; N< 20000; N + = 100){
        上部= DBL_EPSILON * 2;
        低级= 0;
        总= 0;
        而(上< FLT_MAX){
            总=总+ TRA(上,下,N);
            低=上;
            上=上* 2;
        }
        的printf(整体是%.10f \\ n,总数);
    }
    返回0;
}

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

解决方案

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

这篇关于数值积分,使用C中的梯形规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆