自适应梯形公式(变步长).cpp
Upload User: hks123456
Upload Date: 2014-01-27
Package Size: 18k
Code Size: 1k
Category:

Algorithm

Development Platform:

Visual C++

  1. #include<iostream.h>
  2. #include<math.h>
  3. int n;
  4. float f(float);
  5. void main()
  6. {
  7. float s;
  8. float AutoTrap(float (*)(float),float,float);
  9. s=AutoTrap(f,0.0,1.0);
  10. cout<<"T("<<n<<")="<<s<<endl;
  11. }
  12. float AutoTrap(float (*)(float),float a,float b)
  13. {
  14. int i;
  15. float x,s,h=b-a;
  16. float t1,t2=h/2.0*(f(a)+f(b));
  17. n=1;
  18. do{
  19. s=0.0;
  20. t1=t2;
  21. for(i=0;i<=n-1;i++)
  22. {
  23. x=a+i*h+h/2;
  24. s+=f(x);
  25. }
  26. t2=(t1+s*h)/2.0;
  27. n*=2;
  28. h/=2.0;
  29. }while( fabs(t2-t1)>1e-6);
  30. return t2;
  31. }
  32. float f(float x)
  33. {
  34. return 1/(1+x*x);
  35. }
  36. //用变步长梯形法计算积分积分只要将函数定义为
  37. /*float f(float x)
  38. {
  39. if(x==0)
  40. return 1;
  41. else 
  42. return sin(x)/x;
  43. }*/