Python - AI 助手

Python random.gammavariate() 方法



Python 中的 **random.gammavariate()** 方法生成符合 Gamma 分佈 的隨機數。Gamma 分佈是一個雙引數連續機率分佈族,取決於兩個正引數 alpha (α) 和 beta (β) 的值,這兩個引數都必須大於 0。

Gamma 分佈的機率密度函式 (PDF) 為:

         x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) =  --------------------------------------
            math.gamma(alpha) * beta ** alpha

引數 alpha (α) 定義分佈的形狀。較大的 α 值會導致分佈更分散。而引數 beta (β) 定義分佈的尺度。它影響資料點圍繞均值的分佈。

語法

以下是 **gammavariate()** 方法的語法:

random.gammavariate(alpha, beta)

引數

此方法接受以下引數:

  • **alpha:** 這是 Gamma 分佈的形狀引數,它必須大於 0。

  • **beta:** 這是 Gamma 分佈的尺度引數,它也必須大於 0。

返回值

此方法返回一個符合 Gamma 分佈的隨機數。

示例 1

讓我們看看使用 **random.gammavariate()** 方法從形狀引數為 2 和尺度引數為 3 的 Gamma 分佈中生成隨機數的基本示例。

import random

# Parameters for the gamma distribution
alpha = 2
beta = 3

# Generate a gamma-distributed random number
random_number = random.gammavariate(alpha, beta)

print("Generated random number:", random_number)

以下是輸出:

Generated random number from gamma distribution: 7.80586421115812

**注意:**由於其隨機性,每次執行程式時生成的輸出都會有所不同。

示例 2

此示例使用此方法生成一個包含 10 個隨機數的列表,這些隨機數服從 Gamma 分佈。

import random

# Parameters for the gamma distribution
alpha = 3
beta = 1.5

result = []
# Generate a random numbers from the gamma distribution
for i in range(10):
    result.append(random.gammavariate(alpha, beta))

print("List of random numbers from Gamma distribution:", result)

執行以上程式碼時,您將獲得如下所示的類似輸出:

List of random numbers from Gamma distribution: [1.8459995636263633, 1.5884068672272527, 2.472844073811172, 5.9912332880010375, 5.710796196794566, 7.0073286403252535, 0.6174810186947404, 2.3729043573117172, 3.5488507756541923, 4.851207589108078]

示例 3

以下是一個使用random.gammavariate()方法生成並顯示直方圖的示例,該直方圖顯示了 Gamma 分佈資料的分佈情況。

import random
import numpy as np
import matplotlib.pyplot as plt

# Parameters for the gamma distribution
alpha = 1
beta = 2

# Generate gamma-distributed data
d = [random.gammavariate(alpha, beta) for _ in range(10000)]

# Create a histogram from the generated data, with bins up to the maximum value in d
h, b = np.histogram(d, bins=np.arange(0, max(d)+1))

# Plot the histogram to visualize the distribution
plt.bar(b[:-1], h, width=1, edgecolor='none') 
plt.title('Histogram of Gamma Distributed Data')

# Display the plot
plt.show() 

以上程式碼的輸出如下:

 random gammavariate method
python_modules.htm
廣告