python - Python:在两个值之间生成n个随机整数,总和为给定数字
问题描述
我非常想在两个值 ( , )n
之间生成随机整数,其总和等于给定数字。min
max
m
注意:我在 StackOverflow 中发现了类似的问题;但是,它们并没有完全解决这个问题(Dirichlet
函数的使用以及 0 和 1 之间的数字)。
示例:我需要 0 到 24 之间的 8 个随机数(整数),其中 8 个生成的数字之和必须等于 24。
任何帮助表示赞赏。谢谢。
解决方案
好吧,您可以使用整数分布,它自然地总和为某个固定数字 -多项式。
只需来回移动,它应该会自动工作
代码
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)
推荐阅读
- javascript - Javascript:无法执行新行
- mongodb - Power BI - 在“等待初始通信数据包”时丢失与 MySQL 服务器的连接,系统错误:10060
- javascript - 即使在 VUE 组件中添加外部 JS 后,变量仍然没有定义
- python - 尝试获取记录列表时出现 Django RestAPI 500 错误
- python - Python JoinableQueue 在其他进程中调用 task_done 需要两次
- python - BeautifulSoup Python NoneType 对象没有属性“文本”
- python - 根据另一列出现百分比从熊猫数据框中选择行
- android - Android 11 (SDK 30) 自定义文件选择器库
- python - 分组 Tkinter 标签
- python-3.x - 为什么 sklearn RidgeCV 没有 n_jobs 参数?