//这是一个头文件,
class function
{
public:
virtual double operator() (double x) const = 0;
virtual ~function(){}
};
class myfunction :public function
{
public:
virtual double operator()(double x)const;
};
class integration
{
public:
virtual double operator() (double a,double b,double eps) const = 0;
virtual ~integration(){}
};
class trapz:public integration
{
public:
trapz (const function &f):f(f){}
virtual double operator()(double a, double b, double eps) const;
private:
const function &f;
};
//头文件到此为止
//一个cpp
#include"trapzint.h"
#include<cmath>
double myfunction::operator()(double x)const
{
double d = (log10(1.0 + x)) / (1.0 + x*x);
return d;
}
double trapz::operator()(double a, double b, double eps)const
{
bool done = false;
int n = 1;
double h = b - a;
double tn = h*(f(a) + f(b)) / 2.0;
double t2n;
do {
double sum = 0;
for (int k = 0; k < n; k++)
{
double x = a + (k + 0.5)*h;
sum += f(x);
}
t2n = (tn + h*sum) / 2.0;
if (fabs(t2n - tn) < eps)
done = true;
else {
tn = t2n;
n *= 2;
h /= 2;
}
} while (done);
return t2n;
}
//到此为止
//主函数
#include"trapzint.h"
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
myfunction f;
trapz trapz(f);
cout <<"trapz int:" << setprecision(100) << trapz(0.0, 2.0, 1e-7) << endl;
return 0;
}
//这个程序主要是求积分,最后书上的答案是0.5548952(精度1e-7)
//代码运行结果0.1982271