天天看點

C++利用複化Simpson公式構造的自适應算法計算積分

具體算法詳見參考文獻,本文僅僅給出C++利用複化Simpson公式構造的自适應算法計算積分的具體程式。

simpson.h:

#ifndef SIMPSON_H_INCLUDED
#define SIMPSON_H_INCLUDED
#include <iostream>
#include <math.h>
#include"fuction.h"
using namespace std;
double Simpson(double eps,double lower_bd,double upper_bd)
{
    double h=upper_bd-lower_bd,s,s1,s2;//h為步長
    int n=1,k ;
    s1=h/6*(fuction(lower_bd)+4*fuction((lower_bd+upper_bd)/2)+fuction(upper_bd));
    s=2*fuction(lower_bd+0.25*h)-fuction(lower_bd+0.25*h)+2*fuction(lower_bd+0.75*h);
    s2=0.5*s1+s*h/6;//初始化s、s1、s2
    do
    {
       h=0.5*h;
        n=2*n;
        s1=s2;
        s=0;//為友善求和
        for(k=0;k<n;k++)
        {
             s=s+2*fuction(lower_bd+(k+0.25)*h)-fuction(lower_bd+(k+0.5)*h)+2*fuction(lower_bd+(k+0.75)*h);
        }
        s2=0.5*s1+s*h/6;
    }while (fabs(s2-s1)>eps);

    return s2;
}

#endif // SIMPSON_H_INCLUDED
           

在fuction.h中存放具體的被積函數,下面舉一例

fuction.h:

#ifndef FUCTION_H_INCLUDED
#define FUCTION_H_INCLUDED

#include <iostream>
#include <math.h>

using namespace std;
double fuction(double x)
{
    return pow(4-(pow(sin(x),2)),0.5);
}

#endif // FUCTION_H_INCLUDED 
           

主函數中調用函數Simpson進行計算:

#include <iostream>
#include <iomanip>
#include"simpson.h"
#include"fuction.h"

using namespace std;

int main()
{
    cout<<fixed<<setprecision(10)<<Simpson(1e-10,0,0.25)<<endl;
    return 0;
}
           

經過計算,積分值為0.4987111175。

參考文獻:黃雲清,舒适. 2009.數值計算方法.北京:科學出版社