如何在 Python 中產生總和為特定值的隨機數?

Patricia Arquette
發布: 2024-10-27 20:47:30
原創
273 人瀏覽過

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學習者快速成長!