- #1
Themis
- 7
- 0
Hi
I created a program to run a random walk in 1d with only input the number of steps and the number of walks. I used a random number generator to produce only two outcomes (step forward and step back) and in the main function I want to calculate the average of x (over a number of walks) and the mean square average of x. For that reason I introduced two loops the outer loop for running the number of walks and the inner loop that runs until the number of steps. Finally for each inner loop i want to calculate the x(not the average) and the for each x calculated in each inner loop sum them for the number of walks and then divide them by the number of walks to find the average.
The compilation with g++ was ok but when i run it the results are some random numbers. It doesn't even asks for the inputs. What I am doing wrong? I am an amateur in c++
I created a program to run a random walk in 1d with only input the number of steps and the number of walks. I used a random number generator to produce only two outcomes (step forward and step back) and in the main function I want to calculate the average of x (over a number of walks) and the mean square average of x. For that reason I introduced two loops the outer loop for running the number of walks and the inner loop that runs until the number of steps. Finally for each inner loop i want to calculate the x(not the average) and the for each x calculated in each inner loop sum them for the number of walks and then divide them by the number of walks to find the average.
Code:
//Random Walk in 1-d
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int yo(void) {
int state;
state = 1 + rand() % 2;
return state;
}
int main () {
int nwalks, x,xsum;
int state=0;
int nsteps=0;
double msd=;
double xaverage=0.0;
cout << "Give The number of Steps:" <<endl;
cin >> nsteps;
cout << " Give number of Walks:"<< endl;
cin >> nwalks;
srand(time(0));
xsum=o;
msd=o;
for (int i=1; i <= nwalks; i++){
x=0;
for (int j=1; j <= nsteps; j++){
state = yo();
if (state == 1)
x=x+1;
else
x=x-1;
xsum= xsum + x;
msd= msd + x*x;
}
}
cout << " <x(N)>="<< xsum/nwalks <<" <x^2 (N)="<< msd/nwalks<<endl;
return (0);
}
The compilation with g++ was ok but when i run it the results are some random numbers. It doesn't even asks for the inputs. What I am doing wrong? I am an amateur in c++