# Python: generate k random numbers such that their sum is constant

+4 votes
I want to divide a number (n) into k random numbers such that their sum is n. How can I do this in python?

## 1 Answer

+1 vote
by (354k points)
selected

Best answer

You can divide a number 'n' into random k numbers using either Dirichlet distribution or the multinomial distribution. You need to draw k samples from one of these distributions that will sum to the given number.

Using the multinomial distribution

The below code uses n as the number of experiments in the multinomial distribution. The second parameter is the probabilities of each of the k different outcomes.

>>> import numpy as np
>>> n, k = 132, 5
>>> k_nums = np.random.default_rng().multinomial(n, [1/k]*k, size=1)[0]
>>> print(np.sum(k_nums), k_nums)
132 [29 22 36 23 22]

Using Dirichlet distribution

The below code generates k float values using the Dirichlet() function such that their sum is 1. Then, those float values are multiplied by n and rounded to get integer values.

>>> import numpy as np
>>> n, k = 132, 5
>>> vals = np.random.default_rng().dirichlet(np.ones(k), size=1)
>>> vals
array([[0.37236123, 0.50029459, 0.04043982, 0.02848854, 0.05841581]])
>>> k_nums = [round(v) for v in vals[0]*n]
>>> print(np.sum(k_nums), k_nums)
132 [49, 66, 5, 4, 8]

+2 votes
1 answer
+2 votes
1 answer
+4 votes
1 answer
+3 votes
1 answer
+2 votes
1 answer