Wednesday, March 14, 2018

Mean Square Displacement in 1D Random Walk

Mean Square Displacement in 1D Random Walk

by Maciej Matyka

I realized that calculating MSD (mean square displacement) may be a little tricky for students and beginners. Have a look here, this may help to demistify it a little bit. It is a C++ implementation based on simple 1D random walk.

Reference: https://en.wikipedia.org/wiki/Mean_squared_displacement


-------------------------------------------------------------------------------------------


Results:

Exeplary trajectory of particle in 1D
MSD calculated with the code in this post.



-------------------------------------------------------------------------------------------

/**
 * Mean Square Displacement
 * Definition: https://en.wikipedia.org/wiki/Mean_squared_displacement
 * Implementation by Maciej Matyka
 * 14-03-2018 http://panoramix.ift.uni.wroc.pl/~maq/eng/
 **/

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(void)
{
   srand(time(NULL));

   float x0=0, y0=0;
   float x=x0,y=y0;

   float xn = 0;            // position at step n
   int STEPS = 100000;
   float averagex =0;
   float msd = 0;

   for(int N=0; N<1000; N++)
   {
        averagex =0;
        msd = 0;

        for(int s=0; s<STEPS;s++)
        {
            x=x0;
            for(int t=0; t<N; t++)
            {
                float dx = rand()/float(RAND_MAX);      // 1d random walk
                if(dx>0.5) dx=1; else dx=-1;
                x = x+dx;
            }  
            averagex = averagex + x;
            msd = msd + (x-x0)*(x-x0);
       }
       averagex/=(float)STEPS;
       msd/=(float)STEPS;
       cout << N << "\t" << averagex << "\t" << msd << endl;
   }
}
-------------------------------------------------------------------------------------------

No comments:

Post a Comment

Soda Constructor (Revisited)