Non biased return a list of n random positive numbers (>=0) so that their sum == total_sum

后端 未结 7 1221
天涯浪人
天涯浪人 2020-11-30 12:45

I\'m either looking for an algorithm or a suggestion to improve my code to generate a list of random numbers that their sum equals some arbitrary number. With my code below

7条回答
  •  渐次进展
    2020-11-30 12:50

    Here's how I would do it:

    1. Generate n-1 random numbers, all in the range [0,max]
    2. Sort those numbers
    3. For each pair made up of the i-th and (i+1)-th number in sorted list, create an interval (i,i+1) and compute its length. The last interval will start at the last number and end at max and the first interval will start at 0 and end at the first number in the list.

    Now, the lengths of those intervals will always sum up to max, since they simply represent segments inside [0,max].

    Code (in Python):

    #! /usr/bin/env python
    import random
    
    def random_numbers(n,sum_to):
        values=[0]+[random.randint(0,sum_to) for i in xrange(n-1)]+[sum_to]
        values.sort()
        intervals=[values[i+1]-values[i] for i in xrange(len(values)-1)]
        return intervals
    
    if __name__=='__main__':
        print random_numbers(5,100)
    

提交回复
热议问题