# Random Walk Simulation in 1D for 10 or more particles

This is a discussion on Random Walk Simulation in 1D for 10 or more particles within the C Programming forums, part of the General Programming Boards category; Hello, I have written a code for Random Walk in 1D for 1 particle. And I calculated its Mean square ...

1. ## Random Walk Simulation in 1D for 10 or more particles

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;
}```

2. Perhaps you're starting with garbage...
Code:
```\$ gcc -Wall -Wextra -O2 bar.c
bar.c: In function ‘main’:
bar.c:49: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
bar.c:61: warning: array subscript is above array bounds
bar.c:43: warning: ‘m’ may be used uninitialized in this function

The MSD for 10 particle(s) is: -171906769.316143
The MSD for 1 particle: 101.160000```

Popular pages Recent additions