Python Random Walks Question

Asked 1 years ago, Updated 1 years ago, 339 views

#1, if code is implemented as Python basic type
import random

position = 0
walk = [position]
steps = 1000

for i in range(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)


plt.plot(walk[:1000])
If implemented as #2 np.random
nsteps = 30
draws = np.random.randint(0, 2, size=nsteps)
draws.shape
steps = np.where(draws > 0, 1, -1) #np.where(cond, xarr, yarr) -> if condTrue, xarr, if condFalse, yarr
walk = steps.cumsum() #cumsum is a function that calculates the cumulative sum of elements accumulated according to a given axis in an array

I'm studying this code. Here

for i in range(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)

If the .#1 code is randint 0<=x<=1, it means that 1 or -1 is output.

I can't see the code of counting separately, but if it's random.randint(0,1), it's an integer random number between 0 and 1, so I'm going to print one of 0 and 1. Is there anything other than 0 and -1??

2. Why do you use random.randint(0,1) for #1 and random.randint(0,2) for #2?

When I used random.randint(0,2) in .#1, I was able to draw an increasing graph, but I wonder why it is different.

I'd appreciate it if you could answer me!

python random

2022-10-21 00:00

1 Answers


2022-10-21 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.