简体   繁体   English

如何获得总和等于M的N个随机整数

[英]How to get N random integer numbers whose sum is equal to M

I want to make a list of N random INTEGER numbers whose sum is equal to M number.我想列出 N 个随机整数,其总和等于 M 个数字。

I have used numpy and dirichlet function in Python, but this generate double random number array, I would like to generate integer random number.我在 Python 中使用过 numpy 和 dirichlet 函数,但这会生成双随机数数组,我想生成整数随机数。

import numpy as np 
np.random.dirichlet(np.ones(n))*m

The solution can use other distribution the sense is resolve the problem.解决方案可以使用其他发行版,意义是解决问题。

The problem with using dirichlet for this is that it is a distribution over real numbers.为此使用dirichlet的问题在于它是实数上的分布。 It will yield a vector of numbers in the range (0,1) , which sum to 1, but truncating or rounding them may remove the guarantee of a specific sum.它将产生一个范围为(0,1)的数字向量,其总和为 1,但截断或舍入它们可能会消除对特定总和的保证。 Following this post we can get the desired effect from the multinomial distribution (using np.random.multinomial ), as follows:这篇文章之后,我们可以从multinomial分布(使用np.random.multinomial )中获得所需的效果,如下所示:

from numpy.random import multinomial

np.random.multinomial(m, np.ones(n)/n)

This will generate n integers between 0 and m , whose sum is m , with equal probability of drawing a given position.这将生成0m之间的n整数,其总和为m ,绘制给定位置的概率相等。 The easiest way to visualize this is to consider the result as describing a set of draws from a fixed set of objects (eg, die rolls drawing from the integers from 1 to 6) where the final array is the number of times the corresponding object was drawn.将其可视化的最简单方法是将结果视为描述一组固定对象的绘制(例如,从 1 到 6 的整数绘制的骰子滚动),其中最终数组是相应对象的次数画。 The total will always sum to the given number of total draws (rolls).总和将始终等于给定的总抽奖次数(掷骰子)。

note that a Dirichlet distribution can be used to parametrize a multinomial, giving control over the smoothness or "uniformity" of the bins, eg:请注意,Dirichlet 分布可用于对多项式进行参数化,从而控制 bin 的平滑度或“均匀性”,例如:

import numpy as np 

m = 50
n = 5
s = 0.1

np.random.multinomial(m, np.random.dirichlet(np.ones(n) * s))

mostly parameterised as @Bonfire, but larger values of s (eg try s=100 ) causing the bins to approach Poisson with mean= m/n and smaller values leading to greater variance主要参数化为@Bonfire,但较大的s值(例如尝试s=100 )导致 bin 以均值 = m/n接近泊松,较小的值导致更大的方差

Here is a sample solution:这是一个示例解决方案:

import numpy as np

M = 50 # The fixed sum
N = 5 # The amount of numbers

array = np.random.multinomial(M, np.ones(N) / N)[0]
print(array)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM