//c++ 作业:用两重菜单显示 积分函数和积分方法
#include<iostream>
#include<cmath>
using namespace std;
class Function{
public:
virtual double operator()(double x) const=0;
};
class Function1:public Function{
public:
double operator()(double x) const;
};
double Function1::operator()(double x) const{
return log(1.0+x)/(1.0+x*x);
}
class Function2:public Function{
public:
double operator()(double x) const;
};
double Function2::operator()(double x) const{
return x*x;
}
class Function3:public Function{
public:
double operator()(double x) const;
};
double Function3::operator()(double x) const{
return sin(x);
}
class Function4:public Function{
public:
double operator()(double x) const;
};
double Function4::operator()(double x) const{
return cos(x);
}
class Integration
{
public:
virtual double operator()(double a,double b,double eps)=0;
virtual ~Integration(){}
};
class Trapz1:public Integration
{
private:
Function &f;
public:
Trapz1(Function &fun):f(fun){}
double operator()(double a,double b,double eps)
{
int n=200;
double h=(b-a)/n;
double sum=0,tmp;
for(int i=1;i<n;i++)
{
tmp=2*f(a+i*h);
sum+=tmp;
}
sum=(sum+f(a)+f(b))*h/2;
return sum;
}
};//梯形法求积分
class Trapz2:public Integration
{
private:
Function &f;
public:
Trapz2(Function &fun):f(fun){}
double operator()(double a,double b,double eps)
{
bool done=false;
int n=1;
double h=(b-a);
double tn=h*(f(a)+f(b))/2;
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(tn-t2n)<eps)
done=true;
else
{
n=n*2;
h=h/2;
tn=t2n;
}
}while(!done);
return t2n;
}
};//变步长求积分
class Simpson:public Integration
{
private:
Function &f;
public:
Simpson(Function &fun):f(fun){}
virtual double operator()(double a,double b,double eps)
{
int n=400;
double h=(b-a)/(2*n);
double sum=0;
for(int i=1;i<=(2*n-1);i=i+2)
{
double tmp=4*f(a
c++求积分算法
最新推荐文章于 2024-08-02 19:35:04 发布
本文详细探讨了如何使用C++编程实现数值积分方法,包括梯形法则和辛普森法则,通过实例代码展示了如何计算函数的定积分,为理解和应用数值计算提供了清晰的指导。
摘要由CSDN通过智能技术生成