0

Just started with python, so bear with me for some silly questions. Trying to figure out if the below code actually simulates a 1D random walk motion. The +/- 1 of respective random steps do not seem to add up in results.

Results:

positions: [0, 1, 2, 3, 4, 3]
rr  = [0.38965102 0.88157087 0.60033975 0.84260495 0.44094328] # values to determine if positions should get +/-1

with this code:

import numpy as np
import matplotlib.pyplot as plt

steps = 10
positions = [2]

for i in range(steps):
    rr = np.random.random(steps)
    if rr[i] > 0.5:
        positions.append(positions[i] + 1)
    elif rr[i] < 0.5:
        positions.append(positions[i] - 1

print(positions)
print(rr)
plt.plot(positions)
plt.show()
dboy
  • 1,004
  • 2
  • 16
  • 24
  • `rr = np.random.random(steps)` should be before rather than inside the for loop for efficiency. Doesn't change result, but no reason to keep calling it inside the loop to create stps samples each time. – DarrylG Jul 05 '20 at 17:39

1 Answers1

2

I believe the answer is yes. It does simulate a + / - 1 random walk. Probably not the most effective way to do it with numpy, but it works. Here are a couple of graphs for 10,000 steps:

enter image description here enter image description here

And, here's a different way to achieve the same thing in a more 'numpy-wise' way.

steps = np.random.choice([-1, 1], 1000)
positions = np.cumsum(steps)

plt.plot(positions)
plt.show()
Roy2012
  • 11,755
  • 2
  • 22
  • 35
  • That's great to hear , i am on the right track! I was not aware of some of the "numpy-wise" functions. Good to know! Thank you – montypython Jul 06 '20 at 18:23
  • Glad I could help. If this answers your question, it would be great if you could accept my answer for future generations. – Roy2012 Jul 06 '20 at 18:33