Search code examples
pythonperformancerandomstatistics

Can I pick 5 numbers that add to 1 billion with equal probability without using simulation?


You have 5 choices, and you want to pick from the five choices randomly. Instead of simulating that choice 1 billion times, how would you go about getting numbers for each one directly?

This is the simulation:

choices = [0, 0, 0, 0, 0]
for i in range (int(1e9)):
    choices[random.randint(0, 4)] += 1

But this is quite slow and I don't know how I would get a faster solution.


Solution

  • Sure, you could use distribution which by construction add sampled integer numbers to the fixed sum. Simplest is multinomial distribution

    Python code (untested)

    import numpy as np
    
    a = np.random.multinomial(1000000000, [1/5.]*5, size=1)
    np.sum(a)
    

    another one could be Dirichlet-multinomial distribution