jeudi 4 juin 2015

Generating N uniform random numbers that sum to M

This question has been asked before, but I've never really seen a good answer.

  1. I want to generate 8 random numbers that sum to 0.5.

  2. I want each number to be randomly chosen from a uniform distribution (ie, the simple function below will not work because the numbers will not be uniformly distributed).

    def rand_constrained(n,tot):
        r = [random.random() for i in range(n)]  
        s = sum(r)
        r = [(i/s*tot) for i in r] 
        return r
    
    

The code should be generalizable, so that you can generate N uniform random numbers that sum to M (where M is a positive float). If possible, can you please also explain (or show with a plot) why your solution generates random numbers uniformly in the appropriate range?

Related questions that miss the mark:

Generate multiple random numbers to equal a value in python (current accepted answer isn't uniform--another answer which is uniform only works with integers)

Getting N random numbers that the sum is M (same question in Java, currently accepted answer is just plain wrong, also no answers with uniform distribution)

Generate N random integers that sum to M in R (same question, but in R with a normal--not uniform--distribution)

Any help is greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire