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

后端 未结 7 1232
天涯浪人
天涯浪人 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:56

    I ran into this problem and specifically needed integers. An answer is to use the multinomial.

    import numpy.random, numpy
    total_sum = 20
    n = 6
    
    v = numpy.random.multinomial(total_sum, numpy.ones(n)/n)
    

    As the multinomial documentation explains, you have rolled a fair six-sided dice twenty times. v contains six numbers indicating the number of times each side of the dice came up. Naturally the elements of v have to sum to twenty. Here, six is n and twenty is total_sum.

    With the multinomial, you can simulate an unfair dice as well, which is very useful in some cases.

提交回复
热议问题