Search code examples
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:

    • cut the total range in two randomly, that's b. The odd range is because there are going to be at least 2 below the midpoint and at least 2 above. (This comes from your 1 minimum on each value).
    • cut each of those ranges in two randomly. Again, the bounds are to account for the 1 minimum.
    • return the size of each slice. They'll add up to 40.