Search code examples
juliarandom-walk

Visualizing the 1D random walk in Julia


I would like to know how to plot 1000 "walkers" that each "walk" 100 steps.
I am not sure how to plot a diagram with more then one walker, let alone 1000 each walking 100 steps.

Below is the code for one "walker" walking 10 steps.

function walk(N, init::Int=0)
   trace = Int[init]
   for t in 1:N
       if randn() > 0
          push!(trace, trace[end] + 1)
       else
          push!(trace, trace[end] - 1)
       end
   end

   trace
end
walk(10)
[0, 1, 0, 1, 0, -1, 0, 1, 2, 3, 2]

Solution

  • There are many ways to do it. I would do it like this (this is not a most efficient way to do it, but I find it easy to write):

    using Plots
    init = 0
    walkers = 1000
    walk_length = 100
    walks = cumsum(vcat(fill(init, 1, walkers), # initial state
                        rand([-1, 1], walk_length, walkers)), # vertically append move direction
                   dims=1) # cumulative sum over the first dimension to get one walk per column
    plot(walks, legend=nothing)
    

    In the code walks is a Matrix storing each walk in a column (so in your case it has 101 rows and 1000 columns)