Hi,
I have a code written for simulation of Random Walk in 1D and calculation of its Mean Square Displacement. It does compile, but for some reason, it gives me segmantation fault. I really don't get what is wrong as it seems right to me. Can anyone please have a look and help me to find a bug? Thank you.
Here is the code:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <float.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/times.h>
#define T 1000 /* number of time steps */
#define N 100 /* number of "particles" */
double rndm(void){
return(double)rand()/RAND_MAX;
}
/*Function to increase/decrease position by one in 1D*/
double walk(int start){
double a;
int i,x;
x=start;
a=rndm();
if(a<0.5){ /*Choses which direction to move in*/
x++;
}
else{
x--;
}
return x;
}
int main()
{
FILE *myfilename;
int i,t;
int random[N];
double m;
int xdummy=0,flag=100;
srand(time(NULL));
if((myfilename=fopen("RandomWalk.dat","w"))==NULL){
printf("It didn't succeed to open 'RandomWalk.dat' file.\n");
printf("Exiting...\n");
exit(0);
}
fprintf(myfilename,"#Time| MSD\n");
fprintf(myfilename,"#=========\n");
printf("#Time| MSD\n");
printf("#=====================\n");
/*setup initial configuration (start @ zero)*/
for(i=1;i<=N;i++){
random[i]=0;
}
for(t=1;t<=T;t++){
xdummy++;
m=0.0;
for(i=1;i<=N;i++){
random[i]=walk(random[i]);
/*printf("random[%d]= %d\n",i,random[i]);*/
fprintf(myfilename, "random[%d]= %d\n",i,random[i]);
m+=(random[i]*random[i]);
/*printf("m= %lf\n",m);*/
fprintf(myfilename,"m= %lf\n",m);
}
if(xdummy==flag){
m=m/((double)(N));
/*printf("t= %d, MSD= %lf\n",t,m);*/
printf(" %5d %10.5lf\n",t,m);
fprintf(myfilename,"%5d %lf\n",t,m);
xdummy=0;
}
}
fclose(myfilename);
}