pythonrandom

Generate random numbers summing to a predefined value


How to generate n pseudo-random numbers, so that the sum of them is equal to a particular value?

So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40.

How could this be done in Python? I could generate a random number 1-40, then generate another number between 1 and the remainder, etc, but then the first number would have a greater chance of "grabbing" more.


Solution

  • b = random.randint(2, 38)
    a = random.randint(1, b - 1)
    c = random.randint(b + 1, 39)
    return [a, b - a, c - b, 40 - c]
    

    (I assume you wanted integers since you said "1-40", but this could be easily generalized for floats.)

    Here's how it works: