/* From: "COMPUTATIONAL PHYSICS, 2nd Ed" by RH Landau, MJ Paez, and CC Bordeianu Copyright Wiley-VCH, 2007. Electronic Materials copyright: R Landau, Oregon State Univ, 2007; MJ Paez, Univ Antioquia, 2007; and CC Bordeianu, Univ Bucharest, 2007 Support by National Science Foundation */ // walk.c: Random walk simulation #include #include #include // if you don't have drand48 uncomment the following two lines #define drand48 1.0/RAND_MAX*rand #define srand48 srand #define SQRT2 1.4142135623730950488E0 #define max 10000 #define seed 68111 main() { int i, j; double x, y, r[max+1]; FILE *output; // save data in walk.dat output = fopen("walk.dat","w"); srand48(seed); // seed the number generator // clear array for (i=0; i<=max; i++) r[i]=0.0; for (j=1; j<=100; j++) { // average over 100 trials x = y= 0; // starting point for (i=1; i<=max; i++) { x += (drand48()-0.5)*2*SQRT2; // dx and dy between y += (drand48()-0.5)*2*SQRT2; // -sqrt(2) and sqrt(2) r[i] += sqrt(x*x + y*y); // distance from origin } } for (i=0; i<=max; i++) fprintf(output, "%f\t%f\n", sqrt(i), r[i]/100.); printf("data stored in walk.dat.\n"); fclose(output); }