首页 > 解决方案 > Python:在两个值之间生成n个随机整数,总和为给定数字

问题描述

我非常想在两个值 ( , )n之间生成随机整数,其总和等于给定数字。minmaxm

注意:我在 StackOverflow 中发现了类似的问题;但是,它们并没有完全解决这个问题(Dirichlet函数的使用以及 0 和 1 之间的数字)。

示例:我需要 0 到 24 之间的 8 个随机数(整数),其中 8 个生成的数字之和必须等于 24。

任何帮助表示赞赏。谢谢。

标签: pythonrandominteger

解决方案


好吧,您可以使用整数分布,它自然地总和为某个固定数字 -多项式

只需来回移动,它应该会自动工作

代码

import numpy as np

def multiSum(n, p, maxv):
    while True:
        v  = np.random.multinomial(n, p, size=1)
        q  = v[0]
        a,  = np.where(q > maxv) # are there any values above max
        if len(a) == 0: # accept only samples below or equal to maxv
            return q

N = 8
S = 24
p = np.full((N), 1.0/np.float64(N))

mean  = S / N
start = 0
stop  = 24
n = N*mean - N*start

h = np.zeros((stop-start), dtype=np.int64)
print(h)
for k in range(0, 10000):
    ns = multiSum(n, p, stop-start) + start # result in [0...24]
    #print(np.sum(ns))
    for v in ns:
        h[v-start] += 1

print(h)

推荐阅读