Ask Question
19 September, 00:28

Write a function randomWalk ( ...) which simulates one path (or trajectory) of a simple symmetric random walk with 2N time steps (i. e. from 0,1,2, ...,2N) starting at?0=0.

Input: lengthOfRandomWalk = 2N

Output: samplePath: Array of length 2N+1 with the entire path of the random walk on 0,1,2, ...,2N

+4
Answers (1)
  1. 19 September, 01:43
    0
    import numpy as np

    import random

    import matplotlib. pyplot as plt

    def randomWalk (L):

    # S is a 2d array where x = row1 = S[0][:], y = row2 = S[1][:]

    S = np. zeros (shape = (2, L+1))

    directions = [1,2,3,4]

    for i in range (1, L+1):

    direction = np. random. choice (directions)

    if direction = = 1:

    S[0][i] = S[0][i-1] + 1; S[1][i] = S[1][i-1] # go right

    elif direction = = 2:

    S[0][i] = S[0][i-1] - 1; S[1][i] = S[1][i-1] # go left

    elif direction = = 3:

    S[0][i] = S[0][i-1]; S[1][i] = S[1][i-1] + 1 # go up

    else:

    S[0][i] = S[0][i-1]; S[1][i] = S[1][i-1] - 1; # go down

    samplePath = S

    return samplePath

    n = 100;

    path = randomWalk (2*n)

    print (path)

    x = path[0][:]; y = path[1][:];

    plt. figure (1)

    plt. plot (x, y,'-')

    plt. ylabel ('y')

    plt. xlabel ('x')

    plt. show ()
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a function randomWalk ( ...) which simulates one path (or trajectory) of a simple symmetric random walk with 2N time steps (i. e. ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers