【问题标题】:How can I create three random integers which sum to a specific value? (Python) [duplicate]如何创建三个总和为特定值的随机整数? (Python)[重复]
【发布时间】:2016-04-24 14:03:55
【问题描述】:

假设 bob = 6

我想创建 3 个总和为 106 的随机整数(100 + bob 的原始整数。可能是 10,但在本例中是 6)。

我有:

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

我可以生成整数,但如何确保它们的总和 = 100 + 原始整数? (共 106 个)。如果总和不 = 106,那么我希望脚本继续运行,直到达到 106。

【问题讨论】:

  • 如果bob=201 怎么办?您希望您的脚本持续运行多长时间才能达到 301?
  • 嗨 gboffi,我现在保持简单,但是是的,理论上我希望脚本可以处理任何数字。但现在,我只是保持基本。

标签: python random integer sum


【解决方案1】:

生成加起来等于某个数字的数字的一般方法是这样的:

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]

它在0100 + bob之间选择两个切点,并分配如图所示的数字:

这也将确保所有三个数字具有相同的分布(模拟 1m 次试验):

mean    34.700746   35.639730   35.659524
std     24.886456   24.862377   24.861724

相对于依赖生成的数字:

mean    50.050665   27.863753   28.085582
std     29.141171   23.336316   23.552992

还有他们的直方图:

【讨论】:

    【解决方案2】:

    只计算第三个值:

    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
    

    【讨论】:

    • 谢谢,这就是我想要的。我只需要在第 4 行添加一个额外的 ) 右括号。​​但否则这看起来很完美。谢谢。
    【解决方案3】:
    bob1 = (randint(0,100))
    bob2 = (randint(0,(100-bob1)))
    bob3 = 100 - (bob1 + bob2)
    

    【讨论】:

      【解决方案4】:

      这是一个通用函数,它总是会在 [0, n] 中随机生成 3 个与 n 相加的数字;由于中间值是由"bob" 的初始值决定的,我们将这个值和一个目标总数传递给它。该函数返回一个由 3 个数字组成的元组,这些数字与 bob-initial-value 加起来就是目标:

      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)
      

      样本输出:

      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
      

      如果您愿意,您可以在返回之前random.shuffle(a, b, c),以消除第一个数字可能大于第二个可能大于第三个的可预测性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-07
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        相关资源
        最近更新 更多