Advertisement
Guest User

Lotka-Volterra C++

a guest
Jan 27th, 2014
1,635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<sstream>
  4. #include<iomanip>
  5. using namespace std;
  6.  
  7. const double a = 0.05;
  8. const double b = 0.002;
  9. const double c = 0.06;
  10. const double d = 0.004;
  11.  
  12. const double step = 0.1;
  13.  
  14. const int numberOfLoops = 4000;
  15.  
  16.  
  17. double dxdt(double x, double y){
  18.     return x*(a - b*y);
  19. }
  20.  
  21. double dydt(double x, double y){
  22.     return -y*(c - d*x);
  23. }
  24.  
  25. int main(int argc, char** argv){
  26.    
  27.     // x -> prey
  28.     // y -> predator
  29.    
  30.     double y0Step = 1;
  31.    
  32.     for(int i1 = 0; i1 < 100; i1++){
  33.                
  34.         double x0 = 100;
  35.         double y0 = 10+i1*y0Step;
  36.    
  37.         double x = x0;
  38.         double y = y0;
  39.    
  40.  
  41.         ofstream af;
  42.         stringstream afN; afN << "./txt/xt" << setfill('0') << setw(4) << i1 << ".txt";
  43.         string afName = afN.str();
  44.        
  45.         ofstream bf;
  46.         stringstream bfN; bfN << "./txt/yt" << setfill('0') << setw(4) << i1 << ".txt";
  47.         string bfName = bfN.str();
  48.        
  49.         af.open(afName);
  50.         bf.open(bfName);
  51.  
  52.         for(double i1 = 0; i1 < numberOfLoops * step ; i1 += step){
  53.    
  54.             af << i1 << ' ' << x << endl;
  55.             bf << i1 << ' ' << y << endl;
  56.    
  57.             x0=x;
  58.             y0=y;
  59.    
  60.             x += step * dxdt(x0,y0);
  61.             y += step * dydt(x0,y0);
  62.         }
  63.    
  64.         af.close();
  65.         bf.close();
  66.        
  67.         stringstream commandsToTerminal;
  68.         commandsToTerminal << "gnuplot -p -e \"set term png; set output \'"
  69.                             << "./png/doublePlot" << setfill('0') << setw(4) << i1 << ".png"
  70.                             << "\';plot \'" << afN.str() << "\', \'" << bfN.str() << "\'\" ";
  71.        
  72.         system(commandsToTerminal.str().c_str());
  73.     }
  74.  
  75.  
  76.     system("convert -delay 10 -loop 0 ./png/*.png animation.gif && open -a /Applications/Google\\ Chrome.app/ animation.gif");
  77.    
  78.     // Any argument clears the unnecessary aux files
  79.     if(argc > 1){
  80.         system("rm ./png/* ./txt/*");
  81.     }
  82.  
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement