可以用于近似计算一元函数的定积分,类的实现上采用了函数指针类型,使得应用更为灵活!
typedef double (*pfn)(double);
class integral{
double lower;//积分下限
double upper;//积分上限
pfn integrand;//积分函数
public:
integral(double a,double b,pfn f){
lower=a;
upper=b;
integrand=f;
}
double lowbd()const {return lower;}
double upbd()const {return upper;}
void changebd(double,double);//改变积分上下限
double trapezoidal(int) const;//积分求解,参数限定了步长的大小
friend double simpson(integral,int);//友元函数声明
};
inline void integral::changebd(double a,double b)
{
lower=a;
upper=b;
}
double integral::trapezoidal(int n) const
{
double h=(upper-lower)/n;
double sum=integrand(lower)*0.5;
for(int i=1;i<n;i++)sum+=integrand(lower+i*h);
sum+=integrand(upper)*0.5;
return sum*h;
}
double simpson(integral ig,int n)
{
double h=(ig.upper-ig.lower)/n;
double sum=ig.integrand(ig.lower)*0.5;
for(int i=1;i<n;i++)
sum+=ig.integrand(ig.lower+i*h);
sum+=ig.integrand(ig.upper)*0.5;
double summid=0.0;
for(i=1;i<=n;i++)
summid+=ig.integrand(ig.lower+(i-0.5)*h);
return (sum+2*summid)*h/3.0;
}
本文地址:http://com.8s8s.com/it/it23428.htm