龙贝格算法(Romberg)求定积分(C语言)

  • Post author:
  • Post category:其他


这里写图片描述

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

float f1(float x)
{
    return exp(-x*x);
}

float f2(float x)
{
    return sin(2*cos(x))*sin(x)*sin(x);
}

float f3(float x)
{
    return sin(x)/sqrt(1-0.25*sin(x)*sin(x));
}

float romberg(float a,float b,float(*f)(float),float eps)
{
    int n=1,k;
    float h=b-a,x,temp;
    float T1,T2,S1,S2,C1,C2,R1,R2;
    T1=(b-a)/2*((*f)(a)+(*f)(b));
    while(1)
    {
        temp=0;
        for(k=0;k<=n-1;k++)
        {
            x=a+k*h+h/2;
            temp+=(*f)(x);
        }

        T2=(T1+temp*h)/2;
        if(fabs(T2-T1)<eps)return T2;
        S2=T2+(T2-T1)/3;
        if(n==1)
        {
            T1=T2;
            S1=S2;
            h/=2;
            n*=2;
            continue;
        }
        C2=S2+(S2-S1)/15;
        if(n==2)
        {
            C1=C2;
            T1=T2;
            S1=S2;
            h/=2;
            n*=2;
            continue;
        }
        R2=C2+(C2-C1)/63;
        if(n==4)
        {
            R1=R2;
            C1=C2;
            T1=T2;
            S1=S2;
            h/=2;
            n*=2;
            continue;
        }
        if(fabs(R2-R1)<eps)return R2;
        R1=R2;
        C1=C2;
        T1=T2;
        S1=S2;
        h/=2;
        n*=2;
    }
}

void main()
{
    float eps=5e-6;
    printf("%f\n",romberg(0,0.8,f1,eps));
    printf("%f\n",romberg(0,3.1415926/2,f2,eps));
    printf("%f\n",romberg(0,3.1415926/2,f3,eps));
} 



版权声明:本文为landcruiser007原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。