Loops – Physics – Problem #2
IIT Kharagpur CS10001 / CS11001 Programming and Data Structures Lab Question Archive
Problem Statement
Consider the movement of a particle starting at x = 0. The particle can move either in forward (towards +x), or backward (towards −x), which is randomly selected (like obtaining head or tail in coin tossing). This is a typical observation in several random real life phenomena (e.g. motion of atoms, Brownian motion, etc). Assume that each step of the particle is equal to one unit of distance (i.e. +1 or -1). We wish to compute the expected distance of the particle from the starting point (or how far does the particle travel on the average) after n number of steps. Although apparently it might seem that the average progress will be zero, but actually as n increases, the total distance also increases. You have to write a code to simulate n number of random steps and calculate the final distance dn from the initial step, repeat this process for a large number of iterations (k) and add the square of distance dn in each iteration to get the total distance D. That is, D = Pk n=1 d 2 n . Finally the expected distance DE is computed as, DE = p D/k. Eventually you will see that the total distance covered is approximately the square root of the number of steps. Of course the answer will vary little bit in every execution of the program due to the randomness. For your convenience, the random step generator code is provided as follows. Include the following headers in your code: #include<time.h>, #include<stdlib.h> Add this at the beginning of main( ) function: srand(time(NULL)); Then the following line of code generates +1 or -1 randomly and assigns to variable p: p = rand() & 1 ? -1 : 1; Example: Input: n = 25, k = 100000 Output: 5.00119 Input: n = 100, k = 100000 Output: 10.0023 Input: n = 50, k = 100000 Output: 7.0903