I have seen several posts on this subject already, however they all seem unnecessarily complicated, or wrong --- the following proposal does not suffer from the former problem (it is simple), but possibly the latter (that it is wrong).
My goal is to generate s whole numbers, i.e., positive integers, uniformly at random, such that their sum is n. To me, the following solution of generating n random numbers between 1 and s, and then outputting the frequencies gets what we want:
import random
from collections import defaultdict
samples = list()
for i in range(n) :
samples.append(random.randint(1,s))
hist = defaultdict(int)
for sample in samples :
hist[sample] += 1
freq = list()
for j in range(s) :
freq.append(hist[j+1])
print('list:', freq)
print('sum:', sum(freq))
So, for example, if we wanted s=10 random whole numbers which sum up to n=100, we would get from this procedure, for example
list: [11, 7, 9, 12, 16, 13, 9, 10, 8, 5]
sum: 100
Since I am no statistician by any means, I fear that this generates numbers which are not truly uniformly distributed. Any comments/analysis would be greatly appreciated
Aucun commentaire:
Enregistrer un commentaire