Generate N random numbers within a range with a constant sum

前端 未结 5 869
暗喜
暗喜 2020-12-03 12:26

I want to generate N random numbers drawn from a specif distribution (e.g uniform random) between [a,b] which sum to a constant C. I have tried a couple of solutions I could

5条回答
  •  暖寄归人
    2020-12-03 12:51

    Although this was old topic but I think I got a idea. Consider we want N random number which sum is C and each random between a and b. To solve problem, we create N holes and prepare C balls, for each time we ask each hole "Do you want another ball?". If no, we pass to next hole, else, we put a ball into the hole. Each hole has a cap value: b-a. If some hole reach the cap value then always pass to next hole.

    Example:
    3 random numbers between 0 and 2 which sum is 5.

    simulation result:
    1st run: -+-
    2nd run: ++-
    3rd run: ---
    4th run: +*+
    final:221

    -:refuse ball
    +:accept ball
    *:full pass

提交回复
热议问题