简体   繁体   中英

Does this simulate 1D random walk?

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()

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:

在此处输入图像描述 在此处输入图像描述

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM