mardi 22 septembre 2020

Random generator in python

I want to select one of 0 or 1 based on some probability of getting 1 and some initial seed.

I tried following:

import random

population = [0,1]
random.seed(33)
probabilities = [0.4,0.2,0.5]

def sampleIt():
    selectedProb = random.randrange(0,3,1) #select one of probabilities
    print('Selected Probability: ', selectedProb)
    return random.choices(population, [0, probabilities[selectedProb-1]])

for i in range(100):
    sample = sampleIt()
    print(sample[0])

Below is sample output:

Selected Probability:  0.2
1
Selected Probability:  0.5
1
Selected Probability:  0.4
1
Selected Probability:  0.2
1
Selected Probability:  0.5
1
Selected Probability:  0.2
1

Doubts:

  1. As you can see, it is able to randomly select probabilities. But for each selected probability, it ends up selecting 1 from population. If it selected probability 0.2, then I expect it to select 1 with probability 0.2. In this way, it should have selected 0 at least once. But that is not happening. Why is this so?

  2. Is seed correct set or we have to set differently?

  3. Also, what changes I need to do if I expect sampleIt() to be called from different threads?

  4. Also is there any standard practice to improve performance, say if I run this millions of time? Do I have to use numpy for random number generation?

  5. Does random.randrange() and random.choice() follow uniform distribution?

You can run code online here.




Aucun commentaire:

Enregistrer un commentaire