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

依然范特西╮ 提交于 2021-02-10 20:21:58

问题


I want to make a list of N random INTEGER numbers whose sum is equal to M number.

I have used numpy and dirichlet function in Python, but this generate double random number array, I would like to generate integer random number.

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

The solution can use other distribution the sense is resolve the problem.


回答1:


The problem with using dirichlet for this is that it is a distribution over real numbers. 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. Following this post we can get the desired effect from the multinomial distribution (using np.random.multinomial), as follows:

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. The easiest way to visualize this is to consider the result as describing a set of draws from a fixed set of objects (e.g., die rolls drawing from the integers from 1 to 6) where the final array is the number of times the corresponding object was drawn. The total will always sum to the given number of total draws (rolls).




回答2:


note that a Dirichlet distribution can be used to parametrize a multinomial, giving control over the smoothness or "uniformity" of the bins, e.g:

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 (e.g. try s=100) causing the bins to approach Poisson with mean=m/n and smaller values leading to greater variance




回答3:


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)


来源:https://stackoverflow.com/questions/59148994/how-to-get-n-random-integer-numbers-whose-sum-is-equal-to-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!