f0611.cpp
资源名称:c.rar [点击查看]
上传用户:puke2000
上传日期:2022-07-25
资源大小:912k
文件大小:1k
源码类别:

C#编程

开发平台:

Visual C++

  1. //==================================
  2. // f0611.cpp
  3. // 辛普生积分
  4. //==================================
  5. #include<iostream>
  6. #include<fstream>
  7. #include<cmath>
  8. using namespace std;
  9. //----------------------------------
  10. double g(double x){
  11.   return 1/x;
  12. }//---------------------------------
  13. double simpson(double a, double b, double(*f)(double)){
  14.   double I2n=0,h=b-a,T2n=h*(f(a)+f(b))/2,In=T2n,Tn;
  15.   for(int n=1; abs(I2n-In)>1e-3; n+=n,h/=2.0){
  16.     In=I2n; Tn=T2n;       // In老积分值
  17.     double sigma=0;
  18.     for(int k=0; k<n; k++)
  19.       sigma += f(a+(k+0.5)*h);
  20.     T2n=(Tn+h*sigma)/2;
  21.     I2n=(4*T2n-Tn)/3;     // I2n新积分值
  22.   }
  23.   return I2n;
  24. }//---------------------------------
  25. int main(){
  26.   ifstream in("integral.txt");
  27.   cout<<fixed; cout.precision(3);
  28.   for(double b; in>>b; )
  29.     cout<<simpson(1,b,g)<<"n";
  30. }//=================================
  31.