Random walking on a torus


/ Published in: C
Save to your folder(s)

% gcc -lm rndwalk-torus.c
% ./a.out 1000 > rnd1.data
% gnuplot
gnuplot> splot "rnd1.data" with line


Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <math.h>
  5.  
  6. #define R (M_PI*4)
  7. #define r (M_PI*2)
  8.  
  9. int main(int argc, char **argv)
  10. {
  11. int i, step;
  12. double x=R+r, y=0.0, z=0.0;
  13. double theta=0.0, phi=0.0, omega;
  14.  
  15. if(argc!=2 || (step=atoi(argv[1]))<=0){
  16. fprintf(stderr, "Usage: %s <step-number>\n", argv[0]);
  17. exit(EXIT_FAILURE);
  18. }
  19.  
  20. srand((unsigned)time(NULL));
  21. printf("%.3f\t%.3f\t%.3f\n", x, y, z);
  22. for(i=0; i<step; i++){
  23. omega=(double)rand() / (double)RAND_MAX * M_PI*2;
  24. theta+=cos(omega)/R;
  25. if(theta<0) theta+=M_PI*2;
  26. else if(theta>M_PI*2) theta-=M_PI*2;
  27. phi+=sin(omega)/r;
  28. if(phi<0) phi+=M_PI*2;
  29. else if(phi>M_PI*2) phi-=M_PI*2;
  30.  
  31. x=(R+r*cos(phi))*cos(theta);
  32. y=(R+r*cos(phi))*sin(theta);
  33. z=r*sin(phi);
  34. printf("%.3f\t%.3f\t%.3f\n", x, y, z);
  35. }
  36.  
  37. return 0;
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.