数值积分2

定步长复合梯形公式

示例代码 test.cpp

#include <iostream>
using namespace std;

double f(double m)
{
    return 4/(1+m*m);
}

int main()
{
    cout<<"输入积分区间[a,b]的a,b"<<endl;
    float a,b;
    cin>>a>>b;

    cout<<"若将区间分成n等分,输入n"<<endl;
    int n;
    cin>>n;

    double h=(b-a)/n;
    double temp=0;
    for(int k=1;k<n;k++)
        temp=temp+f((a+k*h));
    cout<<"Tn="<<(h/2)*(f(a)+2*temp+f(b));

    return 0;
}

Makefile

test:
	g++ test.cpp -o test
clean:
	rm -rf test

编译并运行过程:

$ make
g++ test.cpp -o test
$ ./test 
输入积分区间[a,b]的a,b
2
10
若将区间分成n等分,输入n
4
Tn=1.64949

 

变步长复合梯形公式

示例源代码 test.cpp

#include <iostream>
using namespace std;

float a;
float b;

float f(float x)//积分函数f(x)
{
   return 4/(1+x*x);
}

float T(int t)//递归函数
{
   if(t==1)
        return ((b-a)/2)*(f(a)+f(b));
   else
   {
        float temp=0;
        for (int i=1;i<=t/2;i++)
        {
            float m=f((a+(2*i-1)*(b-a)/t));
            temp=temp+((b-a)/t)*m;
        }
        return 0.5*T(t/2)+temp;
    }
}

int main()
{
    int t=1;

    cout<<"请输入区间[a,b]参数a和b"<<endl;
    cin>>a>>b;

    int k;
    cout<<"输入参数K"<<endl;
    cin>>k;
    for(int i=0;i<k;i++)
        t=t*2;
    cout<<"T1="<<T(1)<<endl;
    for(int i=2;i<=t;i=i*2)
        cout<<"T"<<i<<"="<<T(i)<<endl;
    return 0;
}

Makefile:

test:
	g++ test.cpp -o test
clean:
	rm -rf test

编译并运行过程如下:

$ make
g++ test.cpp -o test
$ ./test 
请输入区间[a,b]参数a和b
1
50
输入参数K
4.6
T1=49.0392
T2=24.6701
T4=12.6469
T8=6.89903
T16=4.37449

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值