在Python中循环生成随机数

时间:2015-01-23 05:56:51

标签: python-2.7 random

这就是事情。

赌徒正在玩一场公平的比赛。在每轮比赛中,他都能以0.5的概率赢钱。现在我们设置游戏轮次数tamx,例如tmax = 20。

我想计算赌徒保持不间断的概率(赌徒在20场比赛后仍有钱)

所以我的想法是编写一个脚本,在20轮游戏后计算赌徒是否被破坏(如果赌徒未被打破,则脚本返回值1)。以下是我的剧本:

from scipy import *
import matplotlib.pyplot as plt
import random as r

tmax = 20
Xi = 10.0               #The initial money the gambler has
t = 0
F = 0
i = 0



while (t < tmax and Xi > 0):

deltaX = r.randint(1, 9)*int(r.sample([-1, 1], 1)[0])   # The change of money during each game round

Xi = Xi + deltaX
t = t + 1
Xf = Xi                             # Final amount of money the gambler      has after the tamx game rouds


if (Xf < 0):
    F = F + 1

我为这个脚本写了一个for循环(例如循环超过100次),然后我在循环中发现赌徒被破坏了多少次。通过这种方式,我们可以找出在20场比赛中被打破的概率。

该脚本运行良好,但是当我为此脚本编写for循环时,在每个循环中,结果与第一个循环相同,

from scipy import *
import matplotlib.pyplot as plt
import random as r

tmax = 20
Xi = 10.0               #The initial money the gambler has
t = 0
F = 0
i = 0

for i in range(0, 100):

    while (t < tmax and Xi > 0):

        deltaX = r.randint(1, 9)*int(r.sample([-1, 1], 1)[0])   # The change of money during each game round

        Xi = Xi + deltaX
        t = t + 1
    Xf = Xi                             # Final amount of money the gambler has after the tamx game rouds


    if (Xf < 0):
        F = F + 1





print F

F的值是100或0,这不是我所期望的。

任何人都可以告诉我为什么会这样,以及如何解决这个问题? 感谢。

1 个答案:

答案 0 :(得分:1)

忘记在for循环后重置xi和t。你得到0或100的原因是因为你基本上只有一个唯一的Xf值,因为你从未回到while循环(因为Xi或t分别是> t max或&lt; = 0)。它应该是:

for i in range(0, 100):
    Xi = 0
    t = 0
    while (t < tmax and Xi > 0):

        deltaX = r.randint(1, 9)*int(r.sample([-1, 1], 1)[0])   # The change of money during each game round

        Xi = Xi + deltaX
        t = t + 1
    Xf = Xi                             # Final amount of money the gambler has after the tamx game rouds