dimanche 10 novembre 2019

Why do the number of iterations matter while generating the random number?

I want to generate a random number using a given function f1(). I have the solution but I am unable to understand the number of iterations required(5 in this case) to generate the random number.

I tried reading other questions and answers but they focused on how to generate a random number(s), not on why a particular technique was followed.

This is my code:

import random


def f1():
    return(random.randint(0, 1))


def f29():
    while(1):
        Res = 0
        for _ in range(0, 5):
            Res = Res << 1 | f1()
        if(Res <= 29):
            return (Res)


print(f29())

I observed one thing: if I change the range of for loop from 5 to 4, only numbers below 20 were appearing, if I changed it to 3, only single digits were appearing. Maybe my observations are anecdotal. My aim is to generate a random number between 0 and 29, inclusive using f1() which generates a random integer: 0 or 1.




Aucun commentaire:

Enregistrer un commentaire