首頁  >  文章  >  後端開發  >  如何產生固定總和、保證均勻分佈的隨機數?

如何產生固定總和、保證均勻分佈的隨機數?

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