python - 使用随机的模拟输出差异
问题描述
我试图通过生成模拟来找到股价从 25 美元跌至 18 美元的预期时间步数。分析表明,所需的预期时间步数为 129。
以下 3 个代码在我看来基本相同,但给出不同的结果。
第一个返回平均 100 个时间步长:
target = 18
support_level = 20
I = []
n = 50000
for i in range(n):
stock_price = 25
t = 0
while stock_price != target:
t += 1
if stock_price < support_level:
stock_price += random.choices([-1, 1], weights=[1/3, 2/3])[0]
if stock_price == support_level:
stock_price += random.choices([-1, 1], weights=[0.1, 0.9])[0]
if stock_price > support_level:
stock_price += random.choices([-1, 1], weights=[2/3, 1/3])[0]
I.append(t)
sum(I) / len(I)
第二个返回平均值 114:
for i in range(n):
stock_price = 25
t = 0
while stock_price != target:
x = random.uniform(0, 1)
t += 1
if stock_price < support_level:
if x <= 2/3:
stock_price += 1
else:
stock_price -= 1
if stock_price == support_level:
if x <= 0.9:
stock_price += 1
else:
stock_price -= 1
if stock_price > support_level:
if x <= 1/3:
stock_price += 1
else:
stock_price -= 1
I.append(t)
第三个返回平均值 129:
for i in range(n):
p=25
t=0
while p != 18:
if(p==20):
dist = [0.1, 0.9]
elif(p>20):
dist = [2/3, 1/3]
else:
dist = [1/3, 2/3]
p=p+random.choices(direction, dist)[0]
t+=1
I.append(t)
sum(I)/len(I)
有什么区别?
解决方案
推荐阅读
- php - Laravel 基于角色在 trait 中处理用户重定向
- rust - 从 rust proc-macro 中获取目标文件夹
- javascript - 总结文本框中所有输入的数字并将其显示在禁用的框中
- android - Socket.io-client 不会从 React Native 移动应用程序连接到服务器
- python - 如何使用 Python 将数据从客户端套接字发送到服务器套接字?
- batch-file - 如何将要在批处理文件中跳过的行数增加 1?
- collision-detection - 检测 NetLogo 中的冲突
- mysql - 从包含随机字符的 mySql 表中删除整个字符串
- matlab - 从 MATLAB 调用 Powershell 不会移动到 MATLAB 中的下一行
- qt - PyQt5 和 QML 中的嵌套 ListView