首页 > 解决方案 > 使用随机的模拟输出差异

问题描述

我试图通过生成模拟来找到股价从 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)

有什么区别?

标签: pythonrandomsimulation

解决方案


推荐阅读