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

Susan Sarandon
發布: 2024-10-27 10:50:30
原創
661 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!