使用 NumPy 生成五個正態分佈的隨機數


在統計學和資料分析的研究中,正態分佈或高斯分佈是一種廣泛使用的機率分佈。它是一個鐘形曲線,描述了機率,通常用於模擬現實世界中的現象。

我們使用 Python 的 NumPy 庫中提供的 random 模組來生成正態分佈的隨機數。它還允許使用者生成具有指定均值和標準差的正態分佈的隨機數。

語法

numpy.random.normal(loc=0.0, scale=1.0, size=None)

引數

loc (浮點數或陣列類):它是分佈的均值或中心。預設值為 0.0,表示生成的鐘形曲線的峰值。

scale (浮點數或陣列類):它是分佈的標準差。預設值為 1.0,它控制鐘形曲線的寬度。

size (整數或整數元組):它返回輸出的形狀,並確定要生成的隨機數的數量。

當提供整數元組時,該函式會生成具有指定形狀的多維隨機數陣列。其預設值為 None。

示例 1

以下示例演示瞭如何生成具有預設均值和標準差的隨機數。

演算法

  • 匯入 numpy 庫。

  • 使用 random.normal 函式,不帶顯式的均值和標準差引數。

  • 將 size 引數指定為 5,以從正態分佈生成五個隨機數。

  • 將生成的隨機數儲存在變數 random_numbers 中。

  • 列印 random_numbers 變數。

import numpy as nmp

# To generate five random numbers from the normal distribution
random_numbers = nmp.random.normal(size=5)

# Print the random numbers
print("The Random Generated Numbers Are:", random_numbers)

輸出

The Random Generated Numbers Are: 
[-0.66362634  0.60882755  0.62147686 -0.0246644   0.17017737]

示例 2

以下程式碼演示瞭如何使用 NumPy 從正態分佈生成十個具有自定義均值和標準差的隨機數。

import numpy as np

# Setting the custom mean and standard deviation
mean = 10  # Mean of the distribution
std_dev = 2  # Standard deviation of the distribution

# Generate the random numbers
random_numbers = np.random.normal(loc=mean, scale=std_dev, size=10)

# Print the generated random numbers
print("Here Are The 10 Generated Random Numbers:", random_numbers)

輸出

Here Are The 10 Generated Random Numbers: 
[10.81862559  7.28414504  8.61239397  8.98294608  7.
50709111  7.90727366  9.21915208 10.43019622 12.493977   11.57399687]

示例 3

在本例中,我們將使用 NumPy 生成一個 4x5 的二維隨機數陣列,這些隨機數來自正態分佈,並具有使用者定義的均值和標準差。

演算法

  • 將 numpy 庫匯入為 np。

  • 設定正態分佈所需的均值和標準差值。

  • 使用 numpy.random.normal 函式,並將均值和標準差值作為引數提供。

  • 將 size 引數指定為元組 (4, 5),以生成一個 4 行 5 列的二維隨機數陣列,這些隨機數來自正態分佈。

  • 將生成的隨機數儲存在變數 random_numbers 中。

  • 列印 random_numbers 變數。

import numpy as nmpy

# Set the mean and standard deviation
mean = 0 
strd_dev = 1 

# Generate a 2D array of random numbers from the normal distribution
random_numbers = nmpy.random.normal(loc=mean, scale=strd_dev, size=(4, 5))

# Print the generated random numbers
print("The two-dimensional array of random numbers:")
print(random_numbers)

輸出

The two-dimensional array of random numbers:
[[-1.18743672 -1.32939008  0.37248625  0.31413006 -0.83207142]
 [-1.26353284  0.4993038  -1.02139944 -0.66408169 -0.40570098]
 [-1.36817096 -0.05267991 -0.33518531 -0.0784531  -0.34882078]
 [ 1.3996869   0.53987652 -2.59857656 -1.2062663  -1.83573899]]

結論

能夠自定義正態分佈的均值和標準差,使其能夠應用於廣泛的用例,例如統計模擬、資料分析、涉及隨機抽樣的蒙特卡羅模擬以估計和分析複雜系統以及金融建模。

在金融和投資分析中,正態分佈通常用於模擬資產收益。它還能夠模擬不同的投資情景和風險評估。

更新於: 2023年8月10日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告