要实现多个步行者,您可以运行另一个循环(尽管这不是我建议的解决方案;请参阅建议的解决方案)。您可以创建一个空的二维 numpy 数组,step_matrix = np.zeros((num_walkers, num_steps))
然后添加一个外循环(内循环填充每个列,外循环移动到下一行)。
...
N = 10 #Number of Steps
d_avg = 0
nw = 2 # number of walkers
# Takes one step per second (Per N)
time = np.arange(N)
position = np.zeros(N)
walkers = np.zeros((nw, N))
for w in range(nw):
for i in range (N-1):
rn = np.random.uniform(0,1) # This generates a random number between (x,y)
if rn < fwd: # If the random number picked is >0.5
step = 1 # move forward 1 step
else:
step = -1 # If the random number picked is not >0.5, then move backwards
position[i+1]=position[i]+step
d_avg+=position[i]
walkers[w, :] = position
...
现在每一行都有每个步行者的位置。
注意:Python 和 scipy / numpy 已经有方法来做这些事情,但不需要嵌套循环。
建议的解决方案:假设所有步行者从 0 开始。
我会这样写多重步行者:
import numpy as np
from __future__ import division # to force division of int to float
num_walkers = 3 # change as needed
num_steps = 10 # change as needed
prob = 0.5
step_matrix = np.random.randint(2, size=(num_walkers, num_steps))
step_matrix[step_matrix < prob] = -1
print step_matrix
印刷:
[[-1 1 -1 -1 -1 1 1 -1 1 1]
[ 1 1 -1 -1 1 -1 -1 1 1 -1]
[-1 -1 1 1 1 -1 -1 -1 -1 1]]
所以没有循环,这给出了一个数组,其中行是步行者,列是步骤。
注意:这些不是您跟踪的每一步的位置,而是每一步移动的方向。
你描述你想要听起来像均方误差(mse)的东西,所以我会尽力而为:
total_displacement = np.sum(step_matrix, axis=1).reshape(num_walkers, 1)
print total_displacement
印刷:
[[ 0]
[ 0]
[-2]]
所以我们有每个步行者的总位移,这只是沿行的总和(步数的总和)。根据您的描述,我们需要从每个单独的步骤中减去该总位移,将该值平方,并将这些平方差中的每一个相加:
mse = np.sum(np.power((step_matrix - total_displacement), 2), axis=1).reshape(num_walkers,1)/num_steps
把这一切都放在一个函数中:
def random_walkers(n_walkers, n_steps, p):
import numpy as np
from __future__ import division # to force division of int to float
step_matrix = np.random.randint(2, size=(n_walkers, n_steps))
step_matrix[step_matrix < p] = -1
total_displacement = np.sum(step_matrix, axis=1).reshape(n_walkers, 1)
positions = np.zeros((n_walkers, n_steps+1))
for i in range(n_steps):
positions[:, i+1] = step_matrix[:, i] + positions[:, i]
mse = np.sum(np.power((step_matrix - total_displacement), 2), axis=1).reshape(n_walkers,1)/n_steps
return step_matrix, mse, positions
mat, mse, pos = random_walkers(2, 5, 0.5)
print mat
print mse
print pos
印刷:
[[ 1 1 -1 -1 1]
[ 1 -1 -1 1 1]]
[[ 1.6]
[ 1.6]]
[[ 0. 1. 2. 1. 0. 1.]
[ 0. 1. 0. -1. 0. 1.]]
这里 pos 是您想要绘制的,因为它会随着时间的推移跟踪实际位置。因此,只需选择一个特定的行,您的情节就会如您所愿。