c++求积分算法

本文详细探讨了如何使用C++编程实现数值积分方法,包括梯形法则和辛普森法则,通过实例代码展示了如何计算函数的定积分,为理解和应用数值计算提供了清晰的指导。
摘要由CSDN通过智能技术生成

//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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值