【问题标题】:Creating a list of n numbers between x and y who sum up to z创建一个包含 x 和 y 之间的 n 个数字的列表,这些数字的总和为 z
【发布时间】:2022-11-22 12:51:27
【问题描述】:

我正在尝试创建一组随机的 25 个数字,这些数字介于 2 到 25 之间,并且在 python 中总和为 100。

This Question 给出了答案,但似乎最大数量永远不会接近 25。

我试过创建一个列表,划分每个数字,然后重新创建列表,但它基本上使我的最小值和最大值无效,因为它们最终几乎总是被大于 1 的数字除:

numbers = np.random.randint(low = 2, high = 25, size = 100, dtype = int)
scale = 100 / sum(numbers) #We want weights to add up to 100%

#Scale values
for value in numbers:
    nums.append(value * scale)

有什么办法吗?谢谢

【问题讨论】:

    标签: python pandas numpy random


    【解决方案1】:

    您尚未指定数字应具有的概率分布,因此这可能是一种简单有效的方法,但不太可能产生接近 25 的数字:

    import numpy as np 
    numbers = np.full(25,2)
    while numbers.sum() < 100:
        i = np.random.randint(25)
        if numbers[i] < 25: # almost guaranteed...
            numbers[i] += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      相关资源
      最近更新 更多