Numpy Assignment Solution

Random Walks

The simulation of random walks provides an illustrative application of utilizing array operations. Let’s first consider a simple random walk starting at 0 with steps of 1 and –1 occurring with equal probability.

Here is a pure Python way to implement a single random walk with 1,000 steps using the built-in random module:

Question 1

Now let's use numpy instead of using for loop to generate the array walk. You are expected to use three lines of code to generate a single random walk with 2,000 steps and save the position after each step in a numpy array walk.

Question 2

Replace the question mark and print out the statistics of the array walk on each line.

Question 3

A more complicated statistic is the first crossing time, the step at which the random walk reaches a particular value. Here we might want to know how long it took the random walk to get at least 10 steps away from the origin 0 in either direction.

You are expected to use two lines of code to return the first crossing time that this walk needs to cross either 10 or -10.

Note the method above may not be efficient since we only want to know the first crossing time in this question.

Question 4

Simulating Many Random Walks at Once

If your goal was to simulate many random walks, say 5,000 of them, you can generate all of the random walks with minor modifications to the preceding code.

Please modify your previous code a little bit to compute all 5,000 random walks with 1000 steps in each and save the result in a two dimensional array walks, in which each row is one walk and each column represnts current position of the walk.

Question 5

Replace the question mark and print out the statistics of the array walks on each line.

Out of these walks, let’s compute the first crossing time to 30 or –30 for each walk. This is slightly tricky because not all 5,000 of them reach 30. Please answer following two questions:

Question 6

Question 7