gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:34:21 25 4
gpt4 key购买 nike

我尝试在 x-y 轴的时间 t=1 上对一维随机游走进行采样,其中 n= 1000 步。每走一步,步行者的位置都会增加或减少 (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)1D Random Walk

# 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

进一步的代码说明

自:

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 并且我们的 down 标志为 True 时我们才会下台(因此 1 成为下限)

上面的(2)相当于:

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

这意味着只有当最后一个位置 < 4 并且 ipp Flag 为 True 时我们才会向上(因此 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%

关于python - 对 x-y 轴上时间 'n= 1000 steps' 为 't=1' 的一维随机游走进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59745114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com