简体   繁体   中英

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.

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 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 (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. 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:

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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