矩形积分和辛普生积分为什么和书上不一样?帮忙看下~
矩形积分:#include<iostream> //???????结果不对???????
#include<fstream>
#include<cmath>
using namespace std;
//--------------------
double g(double x);
double rectangle(double a,double b,double(*f)(double));
//---------------------------------------------------------
int main()
{
ifstream in("integral.txt");
cout<<fixed;
cout.precision(3);
for(double b;in>>b;)
cout<<rectangle(1,b,g)<<endl;
}
//------------------------------
double g(double x)
{
return 1/x;
}
//-------------------------
double rectangle(double a,double b,double(*f)(double))
{
long double w=b-a,sumnew=w*(f(a)+f(b))/2,sumold=0;
for(int n=1;fabs(sumnew-sumold)>=1e-4;n*=2)
{
sumold=sumnew;
sumnew=0;
for(int i=0;i<n;++i)
{
sumnew+=f(a+w*(i+0.5)/n); //共n个小矩形时第i个矩形的中间位置坐标a+w*(i+0.5)/n
sumnew*=w/n; //切割第n次宽度为w/n
}
return sumnew;
}
}
辛普生积分:
#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;
//--------------------
double g(double x);
double simpson(double a,double b,double(*f)(double));
//---------------------------------------------------------
int main()
{
ifstream in("integral.txt");
cout<<fixed;
cout.precision(9);
for(double b;in>>b;)
cout<<simpson(1,b,g)<<endl; //第三个参数为函数指针!!!
}
//------------------------------
double g(double x)
{
return 1/x;
}
//-------------------------
double simpson(double a,double b,double(*f)(double))
{
double h=b-a,t2=h*(f(a)+f(b))/2,t1,i1=t2,i2=0; //i1老积分,i2新积分。
for(int n=1;fabs(i1-i2)>=1e-4;n+=n,h/=2.0)
{
t1=t2;i1=i2;
double sigma=0; //sigma=0初值
for(int i=0;i<n;++i)
sigma+=f(a+h*(i+0.5)); //共n个小矩形时第i个矩形的中间位置坐标a+w*(i+0.5)/n
t2=(t1+sigma*h)/2; //切割第n次宽度为w/n
i2=(4*t2-t1)/3;
return i2;
}
}
integral。txt:
3
27.64738
0.0493
0.99954
0.0000557
100001
书上结果是:
1.099
3.320
-3.010
-0.000
-9.767
11.513