在 x-y 轴上以 'n= 1000 steps' 时间 't=1' 对一维随机游走进行采样

Sample a 1D random walk with 'n= 1000 steps' in time 't=1' in the x-y axis

我尝试在 x-y 轴上以 n= 1000 steps 及时 t=1 对 1D 随机游走进行采样。对于每一步,步行者的位置增加或减少(1/1000)**0.5。我有一个简单的代码,但我不知道如何让它随机添加或减少 (1/1000)**0.5。感谢您的帮助。

import numpy as np
import matplotlib.pyplot as plt
# Generate 500 random steps with mean=0 and standard deviation=1
steps = np.random.normal(loc=0, scale=1.0, size=500)

# Set first element to 0 so that the first price will be the starting stock price
steps[0]=0

# Simulate stock prices, P with a starting price of 100
P = 100 + np.cumsum(steps)

# Plot the simulated stock prices
plt.plot(P)
plt.title("Simulated Random Walk")
plt.show()

改编代码来自 Random Walk (Implementation in Python) and

# Python code for 1-D random walk. 
import random 
import numpy as np 
import matplotlib.pyplot as plt 

# Probability to move up or down 
prob = [0.05, 0.95]   

n = 1000 # number of steps

# statically defining the starting position 
start = 2  
positions = [start] 

# creating the random points 
rr = np.random.random(n) 
downp = rr < prob[0] 
upp = rr > prob[1] 

t = 1

step = (1/n)**0.5

for idownp, iupp in zip(downp, upp): 
    down = step if idownp and positions[-1] > 1 else 0
    up = step if iupp and positions[-1] < 4 else 0
    positions.append(positions[-1] - down + up) 

# plotting down the graph of the random walk in 1D 
x = [i*t/n for i in range(n+1)]
plt.plot(x, positions) 
plt.xlabel('Time (seconds)')
plt.ylabel('Distance')
plt.title(f"Random Walk ({n} steps in {t} seconds)")
plt.grid(True)
plt.savefig("random_walk.png")


plt.show() 

显示

更多代码解释

开始于:

prob = [.05, 0.95]
downp = rr < prob[0]  # Boolean which is True 5% of the time since rr uniform [0, 1)
upp = rr > prob[1]    # Boolean which is True 5% of the time since rr uniform [0, 1)

这为 downp 和 upp 创造了以下可能性

downp  upp
False  False    # 90% of the time
True   False    # 5% of the time
False  True     # 5% of the time

要决定是降级还是升职,我们有以下表达式:

down = step if idownp and positions[-1] > 1 else 0   # (1)
up = step if iupp and positions[-1] < 4 else 0       # (2)

其中step是步长,positions[-1]是最后一个位置

(1) 以上等同于:

if downp and positions[-1] > 1:
    down = step
else:
    down = 0    

这意味着我们只有在最后一个位置 > 1 并且我们的向下标志为 True 时才向下移动(因此 1 成为下限)

(2) 以上等同于:

if ipp and positions[-1] < 4:
    up = step
else:
    up = 0

这意味着我们仅在最后一个位置 < 4 且 ipp Flag 为真(因此 4 成为上限)时才加强

在更新的位置我们有:

positions.append(positions[-1] - down + up)

这意味着:

new_position = positions[-1] - down + up

单步走的可能性是:

down  up           new_position
0      0           positions[-1]              # 90%
step   0           postions[-1] - step        # 5%
0      step        positions[-] + step        # 5%