龙格-库塔算法.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. void main()
  3. {
  4. void Runge_Kutta(float (*f)(float,float),float a,float b,float y0,int N);
  5. float f(float,float);
  6. float a=0,b=5,y0=2;
  7. Runge_Kutta(f,a,b,y0,20);
  8. }
  9. void Runge_Kutta(float (*f)(float x,float y),float a,float b,float y0,int N)
  10. {
  11. float x=a,y=y0,K1,K2,K3,K4;
  12. float h=(b-a)/N;
  13. int i;
  14. cout<<"x[0]="<<x<<'t'<<"y[0]="<<y<<endl;
  15. for(i=1;i<=N;i++)
  16. {
  17. K1=f(x,y);
  18. K2=f(x+h/2,y+h*K1/2);
  19. K3=f(x+h/2,y+h*K2/2);
  20. K4=f(x+h,y+h*K3);
  21. y=y+h*(K1+2*K2+2*K3+K4)/6;
  22. x=a+i*h;
  23. cout<<"x["<<i<<"]="<<x<<"    y["<<i<<"]="<<y<<endl;
  24. }
  25. }
  26. float f(float x,float y)
  27. {
  28. return -x*y*y;
  29. }