首页  >  文章  >  后端开发  >  如何生成固定总和、保证均匀分布的随机数?

如何生成固定总和、保证均匀分布的随机数?

Susan Sarandon
Susan Sarandon原创
2024-10-27 10:50:30663浏览

How to Generate Random Numbers with a Fixed Sum, Guaranteed Uniform Distribution?

生成具有固定总和的随机数

提出的挑战是生成一系列总和等于预定义值的伪随机数。具体来说,如何生成四个数字,加在一起等于 40。

不依赖可能使第一个数字的分布产生偏差的方法,而是采用更统一的方法。该解决方案采用了一种策略,即使用随机选择的除法器将预定义值划分为较小的段。

假设我们有四个随机正整数(e、f、g 和 h),使得 0

e
a = e
b = f - e
c = g - fd = 40 - g

该技术保证每组数字的概率相等,从而确保均匀分布。生成的随机数满足求和到预定义值的要求。

扩展这个概念,以下 Python 函数生成一个正整数随机列表,求和到指定的总数:
<code class="python">import random

def constrained_sum_sample_pos(n, total):
    """Return a randomly chosen list of n positive integers summing to total.
    Each such list is equally likely to occur."""

    dividers = sorted(random.sample(range(1, total), n - 1))
    return [a - b for a, b in zip(dividers + [total], [0] + dividers)]</code>

为了生成非负整数,需要进行额外的转换:
<code class="python">def constrained_sum_sample_nonneg(n, total):
    """Return a randomly chosen list of n nonnegative integers summing to total.
    Each such list is equally likely to occur."""

    return [x - 1 for x in constrained_sum_sample_pos(n, total + n)]</code>

以上是如何生成固定总和、保证均匀分布的随机数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn