Struggling_Student
Struggling_Student

Reputation: 464

step function for 1D random walk in Julia

Let us consider a one-dimensional walk, whose steps are +1 and -1.
The probability to move forward or backward is 50% (in other words p = 1/2)

enter image description here

I would like to code a function step(N) that tells us the position of "L" after N-steps.
My approach:

N = 10
for i in 1:N
if randn() > 0
        i = +1
        print(1)
    else
        i = -1
        print(-1)
    end
end

I get results like: 11-1-11-1-1 etc. In other words these are the steps that our point L takes for N steps. However, I am not sure how to take the sum of all these steps, so that I know where L is. (I am also not sure how to save it as a function).

Upvotes: 2

Views: 306

Answers (4)

gjvdkamp
gjvdkamp

Reputation: 10516

walk = cumsum(rand([-1,1], 10))

using Plots
plot(walk)

Generate random numbers either -1 or 1 and do the running sum of those.

Upvotes: 0

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42234

There is no need to write function of any kind, just use rand

julia> trace = rand([-1,1], 50);

julia> println("Location $(sum(trace)), History : $(join(trace,""))")
Location -6, History : -1-1-1111-111-11-111-1-11-1-1-1-1111-1-1-11-1-1-1-111-1-1-1-111-111111-1-1-1-1

Upvotes: -1

Yuval Warshavsky
Yuval Warshavsky

Reputation: 21

I recommend you initialize 2 integers (left = 0) before the for loop- one for the total steps left, and one for the right. Every time you go left: left += 1 Same goes for the right. Eventually your L will be the absolute difference between left and right. Here's an example in python:

from random import random
def random_steps(n):
    right = 0
    left = 0
    for i in range(n):
        r = random()
        print(r)
        if r > 0.5:
            right += 1
        else:
            left += 1
    print("L = {}".format(right-left))

Upvotes: 2

ForceBru
ForceBru

Reputation: 44878

Just add multiple positions together:

function step(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

You could also preallocate trace since you know the number of elements in it, like trace = Vector{Int}(undef, N + 1) and then insert elements at specific indices.

Sample runs:

julia> step(10)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
 0  -1  -2  -3  -4  -3  -4  -5  -6  -7  -6

julia> step(15)'
1×16 adjoint(::Vector{Int64}) with eltype Int64:
 0  1  2  3  4  3  2  3  4  3  2  3  4  5  6  5

julia> step(20)'
1×21 adjoint(::Vector{Int64}) with eltype Int64:
 0  1  2  1  2  1  2  1  0  1  0  1  0  1  2  1  0  1  0  1  2

Upvotes: 2

Related Questions