本文主要是介绍c++求积分算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//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++求积分算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!