Адаптирующий код из Случайная прогулка (Реализация в Python) и 1D Случайная прогулка
# 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()
Дисплей ![enter image description here](https://i.stack.imgur.com/bKug7.png)
Дальнейшее объяснение кода
С тех пор:
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)
Где шаг - размер шага, а позиции [-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 равен True (таким образом, 4 становится верхней границей) </p>
В обновленной позиции у нас есть:
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%