如何在 Python 中生成总和为特定值的随机数?

Patricia Arquette
发布: 2024-10-27 20:47:30
原创
272 人浏览过

How to Generate Random Numbers that Sum to a Specific Value in Python?

在 Python 中生成与预定义值求和的随机数

所面临的挑战是生成一组伪随机数,这些伪随机数共同求和达到特定值。具体来说,用户希望生成四个数字,总和为 40。

标准解

标准解既统一又可适应不同的目标总和。它采用随机采样来选择满足指定约束的整数序列:

<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>
登录后复制

图形解释

为了说明生成过程,请考虑使用以下方法获取四个正整数总和为 10 的示例constrained_sum_sample_pos(4, 10).

0 1 2 3 4 5 6 7 8 9 10  # The universe.
|                    |  # Place fixed dividers at 0, 10.
|   |     |       |  |  # Add 4 - 1 randomly chosen dividers in [1, 9]
  a    b      c    d    # Compute the 4 differences: 2 3 4 1
登录后复制

结论

标准解决方案提供了一种可靠且统一的方法来生成具有预定义总和的随机数。它可以适应不同的总和值,并可以扩展以处理非负整数。

以上是如何在 Python 中生成总和为特定值的随机数?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!