Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Random walk

  1. Jan 30, 2016 #1

    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 (C):
    //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;
       for (int i=1; i <= nwalks; i++){
          for (int j=1; j <= nsteps; j++){
         state = yo();
         if (state == 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++
  2. jcsd
  3. Jan 30, 2016 #2
    I don't have a computer or a compiler right now, but what happens when you use a block of comments (/* */) to make the compiler ignore everything from "srand(time(0))" and "endl;". Does it ask for input then? You can use this strategy to find out which line of code is doing something you don't want it to.
  4. Jan 30, 2016 #3


    Staff: Mentor

    Your code has syntax errors, so won't compile. The three syntax errors I see are the following
    • double msd=;
    • xsum=o;
    • msd=o;
    In the first line, you're missing the initialization value.
    In the second and third lines, you have used the letter o instead of the numeral 0.

    After I fixed these errors, I ran your code in Visual Studio 2013 and got this output:
    Code (Text):

    Give The number of Steps:
     Give number of Walks:
     <x(N)>=-3 <x^2 (N)=245.429
  5. Jan 30, 2016 #4
    This isn't my question, but I'm curious nonetheless - what could cause g++ to compile something with such obvious errors?
  6. Jan 30, 2016 #5


    Staff: Mentor

    No idea.

    But see my previous post -- I added a bit after you saw it and replied.
  7. Jan 30, 2016 #6
    Yes Sorry for that. those are mistakes i did after i compiled the program and forgot to erase them
  8. Jan 30, 2016 #7
    Any idea why after i corrected the mistakes when i run the program again it produces random numbers and not the same output as yours?
    Is it the compiler? I use g++ because the professor wants it.
  9. Jan 30, 2016 #8
    What happens if you comment out everything apart from the essentials (main fucntion, includes, et cetera) and the requests for input (cout and cin)?
  10. Jan 30, 2016 #9


    Staff: Mentor

    Two different runs of the program should produce different output, even with the same numbers as inputs. That's the nature of using random numbers.
    When I ran your code I entered 20 for the no. of steps and 14 for the no. of walks. Your code has zero comments and no information in the prompts about what these variables are supposed to represent, other than one is steps and the other is walks. A naive user such as myself won't know the difference between these. Comments in your code and more helpful comments would make it easier for a user to know what to enter.

    Your instructor is likely to deduct points if there are no comments in your code.
    As I said, different program runs will produce different output, and the same is true if you use a different compiler.
  11. Jan 30, 2016 #10
    I had the impression that the program only gave randomn numbers and no input prompt? Or do I need to drastically refine my fine-reading skills?
  12. Jan 30, 2016 #11
    Thanks a lot for the your advice I will add comments when i finally run the program.
    My fault I didn't make it clear : When i say it produces random numbers I mean that when i run it, it doesn't ask for inputs, it just makes a list of 24 random numbers and that's it. My output should be 2 numbers x(N) and x^2(N).

    I installed visual studio and it runs now. Don't know why but it works

    How about now ? I added comments
    Code (C):
    //Random Walk in 1-d

    #include <iostream>  // the libraries we need to run the program
    #include <cstdlib>
    #include <ctime>

    using namespace std;
    // The function yo is the random generator that gives two possible states
    // If it gives 1 the guy walks one step forward if 2 it goes one step back
    int yo(void) {

        int state;
        state = 1 + rand() % 2;

        return state;

    // End of random generator function

    int main() {

        int nwalks, x, xsum; // nwalks is the number of walks we want
                             // x is the displacement from the point of origin( we start at zero --see later in loop)
                             // xsum is adding the x's in each inner loop
        int state = 0;    
        int nsteps = 0;
        double msd;          //msd is the mean square displacement

        cout << "Give The number of Steps:" << endl;  // The program asks for input the number of steps we want the guy to walk
        cin >> nsteps;
        cout << " Give number of Walks:" << endl;    // The number of walks input, is how many times we want to repeat the random walk
        cin >> nwalks;

        srand(time(0)); // this is the seed of our generator
        xsum = 0;     // we start our computation of xsum and msd from zero
        msd = 0;
        for (int i = 1; i <= nwalks; i++){ // this loop is for repeating the scenario according to our input of nwalks
            x = 0; // When the inner loop completes each task we want for the next nwalk x to start again from zero
            for (int j = 1; j <= nsteps; j++){ // This is the random walk simulation for nsteps input
                state = yo(); //we set our variable state to take whatever value our random generator gives
                if (state == 1) // If the generator gives 1 then the guy makes a step forward and so we add 1 to x
                    x = x + 1;
                    x = x - 1; // If the generator gives 2 then the guy makes a step back and we subtrack 1 from x

                xsum = xsum + x; // This is the distance the guy has from x=0 after nsteps
                msd = msd + x*x; // This is the x^2 (not the average value)


        //The simulation must calculate the average of x and the average of x^2--so <x>= all x's divided by the nwalks
        // the same stands for the msd
        //We expect that <x> is almost zero (equal propability for back and forward) and <x^2> almost equal to the number of steps
        cout << " <x(N)>=" << xsum/nwalks << " <x^2 (N)>=" << msd/nwalks << endl;

        return (0);
    I have one logical question because the results are not very good. The <x> must be almost zero and the <x^2> almost equal to nsteps in this case.
    The last two equations are in the right place? or to I need something extra?
    xsum = xsum + x; msd = msd + x*x;

    When the inner loop completes (after nsteps) then it calculates xsum and msd. Then it repeats the same for nwalks. I want to add each xsum and msd and divide them by nwalks to take the average. Do i express this correct in my program?

    Sorry Heatherfield i wasn't very clear. I hope with this post i am better

    Thanks a lot again
  13. Jan 30, 2016 #12


    Staff: Mentor

    The two assignment statements (don't call them equations) are in the wrong place. As you say just below, xsum and msd are calculated. This means they should be outside the inner loop
    The calculation for xsum looks OK to me, but I'm not sure about the msd. Is msd for a given run just the square of the current displacement at the end of a walk? If so, then I guess it's OK.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook