我有一个生成一维随机游走的 Matlab 代码。
%% probability to move up or down
prob = [0.05, 0.95];
start = 2; %% start with 2
positions(1) = start;
for i=2:1000
rr = rand(1);
down = rr<prob(1) & positions(i-1)>1;
up = rr>prob(2) & positions(i-1)<4;
positions(i) = positions(i-1)-down + up;
figure(1), clf
plot(positions)
这给了我下面的图1D Random Walk with Matlab
我需要尝试用 Python 翻译它,我想出了这个(使用 numpy):
import random
import numpy as np
import matplotlib.pyplot as plt
prob = [0.05, 0.95] ##probability to move up or down
N = 100 ##length of walk
def randomWalk(N):
positions=np.zeros(N)
start = 2 ##Start at 2
positions[0] = start
for i in range(1,100):
rr = random.randint(0,1)
if rr<prob[0] and positions[i-1]>1:
start -= 1
elif rr>prob[1] and positions[i-1]<4:
start += 1
positions[i] = start
return positions
plt.plot(randomWalk(N))
plt.show()
它看起来非常接近我想要的(见下图):1D Random Walk with Python
但我想知道它们是否真的等价,因为它们看起来确实不同:Python 代码似乎比 Matlab 代码更尖。
我的 Python 代码中缺少什么来实现完美的逐步增加/减少(类似于 Matlab 代码)?也许它需要一个“else”来告诉它保持不变,除非满足这两个条件。我该如何实施?