# Posted By

mustam on 05/22/09

# Statistics

Viewed 85 times
Favorited by 0 user(s)

# Random walking on a torus

/ Published in: C

% 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
`#include <stdio.h>#include <stdlib.h>#include <time.h>#include <math.h> #define R			(M_PI*4)#define r			(M_PI*2) int main(int argc, char **argv){	int i, step;	double x=R+r, y=0.0, z=0.0;	double theta=0.0, phi=0.0, omega; 	if(argc!=2 || (step=atoi(argv[1]))<=0){		fprintf(stderr, "Usage: %s <step-number>\n", argv[0]);		exit(EXIT_FAILURE);	} 	srand((unsigned)time(NULL));	printf("%.3f\t%.3f\t%.3f\n", x, y, z);	for(i=0; i<step; i++){		omega=(double)rand() / (double)RAND_MAX * M_PI*2;		theta+=cos(omega)/R;		if(theta<0)				theta+=M_PI*2;		else if(theta>M_PI*2)	theta-=M_PI*2;		phi+=sin(omega)/r;		if(phi<0)				phi+=M_PI*2;		else if(phi>M_PI*2)		phi-=M_PI*2; 		x=(R+r*cos(phi))*cos(theta);		y=(R+r*cos(phi))*sin(theta);		z=r*sin(phi);		printf("%.3f\t%.3f\t%.3f\n", x, y, z);	} 	return 0;}`