epx
epx

Reputation: 591

Generating random number in loop in Python

Here is the thing.

The gambler is playing a fair game. At each game round, he can win money with the probability 0.5. Now we set the number of game rounds tamx, for example tmax = 20.

I want to calculate the probability of the gambler remains unbroken(the gambler still has money after 20 game rounds)

So my idea is to write a script which calculates the gambler is broken or not after 20 game rounds(If the gambler is not broken, the script returns value 1). Below is my script:

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

And I write a for-loop(loop over 100 times for example) for this script, then I find out during the loop, how many times the gambler is broken. In this way, we can find out the probability of broken under 20 game rounds.

The script works well, but when I write a for loop for this script, during each loop, the result is as same as the first loop,

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

The value of F is either 100 or 0, which is not what I would expect.

Can anyone tells me why this happen and how to fix this? Thanks.

Upvotes: 0

Views: 1261

Answers (1)

mattsap
mattsap

Reputation: 3806

You forgot to reset xi and t after the for loop. The reason why you are either getting 0 or 100 was because there's essentially only one unique Xf value because you never went back into the while loop (because Xi or t were > tmax or <= 0 respectively). It should be:

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

Upvotes: 1

Related Questions