这个问题以前已经被问过了,但我从来没有见过一个好的答案。
I want to generate 8 random numbers that sum to 0.5.
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
与此相关的问题没有解决问题: 在Python中生成多个随机数以达到某个值(目前被接受的答案不是均匀分布——另一个均匀分布的答案只适用于整数) 获取N个随机数,使它们的和为M(Java中的同一问题,目前被接受的答案是完全错误的,也没有任何均匀分布的答案) 在R中生成N个随机整数,使它们的和为M(同样的问题,但在R中使用正常分布而不是均匀分布)
非常感谢您的帮助。