求数字积分源程序
大家好!急需数字积分方面的源程序,请大家给予指导!
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
class F
{
public:
virtual double operator()(double x) const=0;
};
class Fun: public F
{
public:
double operator()(double x)const
{
return log(1.0+x)/(1.0+x*x);
}
};
class Integ
{
public:
virtual double operator()(double a,double b,double eps) const=0;
};
class Trapz:public Integ
{
public:
Trapz(const F &pf):f(pf){};
double operator()(double a,double b,double eps) const;
private:
const F &f;
};
double Trapz::operator()(double a,double b,double eps)const
{
int done(0);
int n;
double h,Tn,T2n;
n=1;
h=b-a;
Tn=h*(f(a)+f(b))/2;
while(!done)
{
double temp(0.0);
for(int k=0;k<n;k++)
{
double x=a+(k+0.5)*h;
temp+=f(x);
}
T2n=(Tn+h*temp)/2;
if(fabs(T2n-Tn)<eps)
done=1;
else
{
Tn=T2n;
n*=2;
h/=2;
}
}
return T2n;
}
void main()
{
Fun f;
Trapz trapz1(f);
cout<<"TRAPZ int:"<<setprecision(7)<<trapz1(0,2,1e-7)<<endl;
}
这个程序是求一个函数的积分