Skip to content Skip to sidebar Skip to footer

How Can I Create Three Random Integers Which Sum To A Specific Value? (Python)

Let's say bob = 6 I want to create 3 random integers that have a sum of 106 (100 + whatever bob's original integer is. It could be 10, but in this case, it's 6). I've got: from ran

Solution 1:

The general approach to generate numbers that add up to a certain number is like this:

import random
bob = 6
numbers = sorted(random.sample(range(100+bob), 2))
bob1 = numbers[0]
bob2 = numbers[1] - numbers[0]
bob3 = 100 + bob - numbers[1]

It selects two cut points between 0 and 100 + bob and assigns the numbers as illustrated:

enter image description here

This will also ensure all three numbers have the same distribution (simulated with 1m trials):

mean    34.700746   35.639730   35.659524
std     24.886456   24.862377   24.861724

As opposed to the numbers generated dependently:

mean    50.050665   27.863753   28.085582
std     29.141171   23.336316   23.552992

And their histograms:

enter image description here


Solution 2:

Just calculate the third value:

from random import randint
bob = 6
bob1 = randint(0, 100)
bob2 = randint(0, min(100, 100 + bob - bob1))
bob3 = 100 + bob - bob1 - bob2
print bob1
print bob2
print bob3

Solution 3:

bob1 = (randint(0,100))
bob2 = (randint(0,(100-bob1)))
bob3 = 100 - (bob1 + bob2)

Solution 4:

Here is a general function that will always randomly generate 3 numbers in [0, n] that add to n; as the intermediate values are determined by "bob"'s initial value, we pass it this value and a target total number. The function returns a tuple of 3 numbers that together with bob-initial-value add up to the target:

import random

def three_numbers_to_n(bob, target):
    n = target - bob
    a = random.randrange(0, n+1)
    b = random.randrange(a, n+1) - a
    c = n - a - b
    return a, b, c

for _ in range(5):
    bob = 6
    result = three_numbers_to_n(bob, 106)
    print(bob, result, sum(result) + bob)

sample output:

6 (13, 3, 84) 106
6 (45, 49, 6) 106
6 (27, 2, 71) 106
6 (44, 18, 38) 106
6 (100, 0, 0) 106

If you wish, you could random.shuffle(a, b, c) before returning to remove the predictability that the first number is likely larger than the second likely larger than the 3rd.


Post a Comment for "How Can I Create Three Random Integers Which Sum To A Specific Value? (Python)"