Ask Question
11 March, 19:18

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

+2
Answers (1)
  1. 11 March, 23:14
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers