定步长复合梯形公式
示例代码 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