jeudi 25 mars 2021

Is randint function in Python different from % trick?

I appreciate your help in advance.

I wrote a probability calculator with python. Prob I want to calculate is this: What's the prob of winning when you try 6 times of game that has winning chance of 1%. So this following code is what I wrote.

import random as rand

total = 0
count = 0

p = pSum = 0

k = 6
n = 10000
m = 100

def pick(attemptPerIteration):
    global total, count
    for _ in range(attemptPerIteration):
        temp = rand.randint(1, 100)
        if (temp == 1):
            count += 1
            total += 1
            return 0
    return 1

for t in range(m):
    for u in range(n):
        total += pick(k)
    p = count / total
    print(str(t + 1) + ": " + str(p * 100))
    pSum += p
    p = 0
print(pSum / m * 100)

In this code, I used randint function to simulate one in 100 chance. The prob I expected is about 5.8% but this program outputs about 6.3%. But if I use randint(1, 1000) % 6 + 1 insted of just randint(1, 6), program tell the prob is 5.8, which I expected.

What's going on in this randint function exactly? Why the old % trick works but randint doesn't?

Mathematical formula to this problem is this: enter image description here




Aucun commentaire:

Enregistrer un commentaire