使用 NumPy 隨機(jī)生成矩陣
在科學(xué)計(jì)算領(lǐng)域中,隨機(jī)數(shù)生成是一種常見的需求。在 Python 中,NumPy 庫提供了眾多生成隨機(jī)矩陣的函數(shù),可以輕松地實(shí)現(xiàn)隨機(jī)數(shù)生成。本文將詳細(xì)介紹 NumPy 中生成隨機(jī)矩陣的各種方法。
- np.random.rand()
np.random.rand() 函數(shù)用于返回 [0, 1) 之間的隨機(jī)浮點(diǎn)數(shù),其形狀由傳入的參數(shù)決定。當(dāng)傳入一個(gè)整數(shù) n 時(shí),該函數(shù)將返回一個(gè)形狀為 (n,) 的一維數(shù)組;當(dāng)傳入兩個(gè)整數(shù) m 和 n 時(shí),該函數(shù)將返回一個(gè)形狀為 (m, n) 的二維數(shù)組。例如:
import numpy as np
# 生成 3 個(gè)隨機(jī)數(shù)
a = np.random.rand(3)
print(a)
# 生成 2x3 的隨機(jī)矩陣
b = np.random.rand(2, 3)
print(b)
執(zhí)行上述代碼,可以得到如下結(jié)果:文章來源:http://www.zghlxwxcb.cn/news/detail-434874.html
[0.2621694 0.62861256 0.28465969]
[[0.83334357 0.84885107 0.28359312]
[0.85877295 0.76776167 0.09972184]]
- np.random.randn()
np.random.randn() 函數(shù)用于生成標(biāo)準(zhǔn)正態(tài)分布的隨機(jī)數(shù)組,也即均值為 0,方差為 1 的正態(tài)分布。與 np.random.rand() 類似,其形狀由傳入的參數(shù)決定。例如:文章來源地址http://www.zghlxwxcb.cn/news/detail-434874.html
import numpy as np
# 生成 3 個(gè)隨機(jī)數(shù)
a = np.random.randn(3)
print(a)
# 生成 2x3 的隨機(jī)矩陣
b = np.random.randn(2, 3)
print(b)
<
到了這里,關(guān)于使用 NumPy 隨機(jī)生成矩陣的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!