Hello,
I have written a code for Random Walk in 1D for 1 particle. And I calculated its Mean square Density for 1 particle. Now I am trying to calculate the MSD for 10 particles, but I get something wrong. The value of MSD should increase when the particles are added. But unfortunately, I get almost the same numbers. Can anyone please have a look and see what is wrong with the code? here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 100 /*flipping 100 times*/
#define T 10 /*for 10 particles*/
double rndm(void)
{
return(double)rand()/RAND_MAX;
}
/*Function to simulate random walk in 1D*/
double walk(int start)
{
double a;
int i,x;
x=start;
for(i=0; i<N; i++)
{
a=rndm();
if(a<0.5) /*Choses which direction to move in*/
x++;
else
x--;
}
return x;
}
/*Main Function*/
int main () {
FILE *fout;
int i,j,start,random[N],x;
double m;
srand(time(NULL));
fout=fopen("Walk.txt", "w"); //Open The File
printf("What would you like the initial x position to be?\n:");
scanf("%d", &start); //Define Start position for x
for(j=1;j<=T;j++){
for(i=0; i<N; i++) {
x=walk(start); // Generates Random Number
random[i]=x;
fprintf(fout, "%d\n", random[i]); // Writes Number To File
}
m+=(random[i]-start)*(random[i]-start); /*MSD for 10 particles*/
m=m/T;
fprintf(fout, "The MSD for %d particle(s) is: %lf\n",j,m);
}
double p = 0;
for (i=0; i<N; i++){
p+=(random[i]-start)*(random[i]-start);}
p=p/N;
fprintf(fout, "The MSD for 1 particle: %lf\n",p); /*Here I calculate MSD for 1 particle*/
fclose(fout);
return 0;
}