Random Walk

Hi, i am writing a piece of code that performs a random walk for N particles (N is a user input), my current piece of code does the random walk for a particle and then moves onto the next one. I would like it to perform the walk so that all the particles are taking steps one after the other. Any help would be much appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <ctime>
#include <cstdlib>
#include<iostream>
#include<cmath>
#include<iomanip>
#include<fstream>

using namespace std;

double dist(int a, int b);

int main() {
int randx=0, randy=0;
int x=0;
int y=0;
int j;
int n,N,u=0,d=0,l=0,r=0;

cout<< "How many particles does your system consist of? " << endl ;
cin >> N ;
cout<< "How steps would you like to take? " ;
cin >> n ;

cout<< "Step number" << setw(3) << "x" << setw(3) << "y" << " Distance" << endl;
cout << setw(11) << 0 << setw(3) << randx << " " << setw(2) << randy << " " << setw(8) << 0 << endl;

ofstream out;
ofstream dis;
out.open ("rwalk.txt");
dis.open ("distance.txt");

  srand(time(0));
  
for (int j=1 ; j<=N ; j++){

  for (int i=1 ; i<=n ; i++){
 
         int ran=rand() % 2;
   
    if (ran==0){
  
        randx = rand() % 2;
        randy = 0;
	   
      if ( randx == 0){
   
          randx=randx-1;
	      l=l+1;
		  
      }else if ( randx==1){
	  
            r=r+1;
      }
      
    }else if (ran==1){
  
         randy = rand() % 2;
         randx = 0;
 
       if ( randy == 0){
   
           randy=randy-1;
	       d=d+1;
		   
       }else if ( randy==1){
	   
           u=u+1;
       }
  	 
    }
   x=x+randx;
   y=y+randy;
   double z=dist(x,y);
   cout  << setw(11) << i << setw(3) << randx << " " << setw(2) << randy << " " << setw(8) << z << endl;
   out << setw(2) << x << " " << setw(2) << y << " " << z << endl;
   dis << z << endl;
   
  }
 
double z=dist(x,y);
 
 cout<< "------------------------------------------------------"<< endl;
 cout<< "    Final x" << " Final y" << " Distance" << endl;
 cout<< setw(11) << x << " " << setw(7) << y << " " << setw(8) << z << endl;
 cout<< u << " " << d << " " << l << " " << r << endl;
 cout<< "------------------------------------------------------"<< endl;
 
 dis.close();
}
out.close();
}

double dist(int a, int b){

double c=sqrt(a*a + b*b);

return c;
}



bump
Topic archived. No new replies allowed.