# Random Walk Simulation in 1D - Undesired output

This is a discussion on Random Walk Simulation in 1D - Undesired output within the C Programming forums, part of the General Programming Boards category; Hello Guys, I am struggling with the code for simulation of Random Walk in 1D. It compiles, but the output ...

1. ## Random Walk Simulation in 1D - Undesired output

Hello Guys, I am struggling with the code for simulation of Random Walk in 1D. It compiles, but the output to text file "Walk.txt" are all almost the same negative numbers. BTW I am a new to C programming, if you could look at the code and give your ideas about what is wrong with it. Here is the code itself:

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 10

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=x+1);
}
if (a>0.5) {
(x=x-1);
}
}
return x;
}

/*Main Function*/

int main () {
FILE *fout;
int i,start,random[N],x;
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(i=0; i<N; i++) {

x=walk(start);       // Generates Random Number
random[i]=x;
fprintf(fout, "%d\n", random[i]);   // Writes Number To File
}

double p = 0;
for (i=0; i<N; i++){
p+=(random[i]-start)*(random[i]-start);}
p=p/N;
fprintf(fout, "%lf\n",p);
fclose(fout);
return 0;

}```
In this part, i've tried to calculate the mean square displacement (position):

Code:
```double p = 0;
for (i=0; i<N; i++){
p+=(random[i]-start)*(random[i]-start);}
p=p/N;
fprintf(fout, "%lf\n",p);
fclose(fout);
return 0;

}```
And the output in "Walk.txt" is :

Code:
```-1079135414
-1079135418
-1079135418
-1079135406
-1079135418
-1079135416
-1079135418
-1079135416
-1079135414
-1079135416
12.400000```

2. (x=x+1);
Do not put parens around a statement for no reason. In fact, you should be using the increment operator here.
x++;
Same for (x=x-1);, replace it with x--;

In walk, use an if/else like this:
Code:
```if (a<0.5)
x++;
else
x--;```
But your program seems to essentially work for me. Here's the output I got:
102
102
100
94
98
100
100
98
98
110
15.600000

3. oogabooga, thank you very much, it did work now, I dont really get why it didnt before if you say it ran fine in urs. But apparently, something was wrong with my code. When I put your statement, it gave the desired output. thank you.