Python - AI 助手

Python random.gauss() 方法



Python 中的random.gauss()方法生成服從高斯分佈(也稱為正態分佈)的隨機數。它是一族連續機率分佈,取決於兩個引數musigma的值。其中,mu是高斯分佈的均值,sigma是高斯分佈的標準差。這種分佈經常用於統計學、資料分析和各個科學領域,包括自然科學和社會科學。

此方法比random.normalvariate()方法更快,後者用於從高斯(正態)分佈生成隨機數。

語法

以下是 Python random.gauss()方法的語法:

random.gauss(mu, sigma)

引數

此方法接受以下引數:

  • mu: 這是高斯分佈的均值。它定義了資料點分佈的中心。

  • sigma: 這是高斯分佈的標準差。它決定了分佈的散佈;較大的標準差會導致較寬的分佈。

返回值

此方法返回一個服從高斯分佈的隨機數。

示例 1

讓我們來看一個使用 Python random.gauss()方法從均值為 0、標準差為 1 的高斯分佈生成隨機數的基本示例。

import random

# mean
mu = 0  
# standard deviation
sigma = 1  

# Generate a Gaussian-distributed random number
random_number = random.gauss(mu, sigma)

# Print the output
print("Generated random number from Gaussian-distribution:",random_number)

以下是輸出:

Generated random number from Gaussian-distribution: 0.5822883447626581

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

示例 2

此示例使用random.gauss()方法生成一個包含 10 個服從高斯分佈的隨機數的列表。

import random

# mean
mu = -2 

# standard deviation
sigma = 0.5  

result = []
# Generate a list of random numbers from the Gaussian distribution
for i in range(10):
    result.append(random.gauss(mu, sigma))

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

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

List of random numbers from Gaussian distribution: [-1.6883491787714924, -2.2670950449189835, -1.68497316636885, -2.62956757323328, -1.8888429377204585, -2.6139116413700765, -2.287545626016553, -1.5470101615690448, -2.259090829777413, -1.9380772732164955]

示例 3

這是一個使用random.gauss()方法的另一個示例,它演示瞭如何改變均值和標準差會影響高斯分佈的形狀。

import random
import matplotlib.pyplot as plt

# Define a function to generate and plot data for a given mu and sigma
def plot_gaussian(mu, sigma, label, color):

    # Generate Gaussian-distributed data
    data = [random.gauss(mu, sigma) for _ in range(10000)]

    # Plot histogram of the generated data
    plt.hist(data, bins=100, density=True, alpha=0.6, color=color, label=f'(mu={mu}, sigma={sigma})')

fig = plt.figure(figsize=(7, 4))

# Plotting for each set of parameters
plot_gaussian(0, 0.2, '0, 0.2', 'blue')
plot_gaussian(0, 1, '0, 1', 'red')
plot_gaussian(0, 2, '0, 2', 'yellow')
plot_gaussian(-2, 0.5, '-2, 0.5', 'green')

# Adding labels and title
plt.title('Gaussian Distributions')
plt.legend()

# Show plot
plt.show()

上述程式碼的輸出如下所示:

random gauss method
python_modules.htm
廣告