具体算法详见参考文献,本文仅仅给出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.数值计算方法.北京:科学出版社