How can I create three random integers which sum to a specific value? (Python) [duplicate]

半世苍凉 提交于 2020-01-07 01:49:40

问题


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 random import *
bob = 6
bob1 = (randint(0,100))
bob2 = (randint(0,100))
bob3 = (randint(0,100))
print bob1
print bob2
print bob3

I can generate integers, but how can I make sure the sum of them = 100 + original integer? (106 total). If the sum doesn't = 106, then I want the script to keep going until it makes 106.


回答1:


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



回答2:


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:

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:




回答3:


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



回答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.



来源:https://stackoverflow.com/questions/36824129/how-can-i-create-three-random-integers-which-sum-to-a-specific-value-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!