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

后端 未结 7 1233
天涯浪人
天涯浪人 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 13:00

    The following is quite simple, and returns uniform results:

    def gen_list(numbs, limit_sum):
        limits = sorted([random.uniform(0, limit_sum) for _ in xrange(numbs-1)])
        limits = [0] + limits + [limit_sum]
        return [x1-x0 for (x0, x1) in zip(limits[:-1], limits[1:])]
    

    The idea is simply that if you need, say, 5 numbers between 0 and 20, you can simply put 4 "limits" between 0 and 20, and you get a partition of the (0, 20) interval. The random numbers that you want are simply the lengths of the 5 intervals in the sorted list [0, random1, random2, random3, random4, 20].

    PS: oops! looks like it's the same idea as MAK's response, albeit coded without using indexes!

提交回复
热议问题