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.
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 multinomialnp.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).