如何在 Python 中建立隨機整數矩陣?


在 Python 中,您可以使用 NumPy 庫建立隨機整數矩陣。NumPy 是一個功能強大的 Python 科學計算庫,它提供了對多維陣列的支援,以及其他功能。

要使用 NumPy 建立隨機整數矩陣,您可以使用 **numpy.random.randint()** 函式。此函式生成指定範圍內的隨機整數,並返回指定形狀的 NumPy 陣列。要生成的整數範圍使用函式的 low 和 high 引數指定。

要指定矩陣的形狀,可以使用 **numpy.random.randint()** 函式的 size 引數。size 引數接受一個元組,該元組指定矩陣的維度。例如,如果您想建立一個 3x3 矩陣,則將 (3, 3) 作為 size 引數的值傳遞。

一旦您指定了矩陣的範圍和形狀,就可以呼叫 **numpy.random.randint()** 函式來生成隨機整數矩陣。該函式返回一個 NumPy 陣列,可以將其儲存在變數中。

語法

以下是關於 randint() 函式的語法。

numpy.random.randint(low, high=None, size=None, dtype='l') 
  • **low** - 矩陣中要生成的最小(包含)整數。

  • **high** - 矩陣中要生成的最高(不包含)整數。如果未指定,則最高整數將比 low 值大 1。

  • **size** - 作為元組生成的矩陣的形狀。例如,(3, 3) 將生成一個 3×3 矩陣。

  • **dtype** - 輸出陣列的資料型別。預設情況下,它設定為 l 表示整數。

現在讓我們探索如何在 Python 中建立隨機整數的不同示例。

示例

請考慮以下程式碼。

# First, we import the NumPy library as 'np'
import numpy as np

# Then, we use NumPy's random.randint() function to generate an array of 20 random integers between 0 and 9 (inclusive).
array = np.random.randint(low=0, high=10, size=20)

# Finally, we print the generated array to the console.
print(array) 

解釋

  • 首先,使用 import numpy as np 行匯入 NumPy 庫。

  • np.random.randint() 函式被呼叫,其引數為 low=0、high=10 和 size=20。這將生成一個包含 20 個介於 0 和 9(含)之間的隨機整數的陣列。

  • 生成的陣列儲存在變數 array 中。

  • print() 函式用於將 array 變數的內容列印到控制檯。

輸出

執行後,您將獲得一個隨機數矩陣 -

[7 1 4 7 6 8 9 9 0 5 5 6 1 0 2 4 2 9 1 2] 

示例

請考慮以下程式碼。

# First, we import the NumPy library as 'np'
import numpy as np

# Then, we use NumPy's random.randint() function to generate a 2x3 matrix of random integers between 0 and 9 (inclusive).
array = np.random.randint(low=0, high=10, size=(2, 3))

# Finally, we print the generated matrix to the console.
print(array)

解釋

  • 使用 import numpy as np 行匯入 NumPy 庫。

  • np.random.seed() 函式被呼叫,其引數為 42。這將設定 NumPy 隨機數生成器的隨機種子,確保每次執行程式碼時都生成相同的隨機數。

  • np.random.randint() 函式被呼叫,其引數為 low=0、high=10 和 size=(3, 3)。這將生成一個 3x3 矩陣,其中包含介於 0 和 9(含)之間的隨機整數。

  • 生成的矩陣儲存在變數 matrix 中。

  • print() 函式用於將 matrix 變數的內容列印到控制檯。

輸出

執行後,您將獲得如下輸出 -

[[9 5 7]
 [0 6 1]]

示例

現在讓我們再舉一個例子。請考慮以下程式碼。

# First, we import the NumPy library as 'np'.
import numpy as np

# Then, we use NumPy's random.randint() function to generate a 5x5 matrix of random integers consisting of only 0s and 1s.
array = np.random.randint(low=0, high=2, size=(5, 5))

# Finally, we print the generated matrix to the console.
print(array)

解釋

  • 首先,使用 import numpy as np 行匯入 NumPy 庫。

  • np.random.rand() 函式被呼叫,其引數為 3 和 4。這將生成一個 3×4 矩陣,其中包含介於 0 和 1 之間的隨機浮點數。

  • 生成的矩陣儲存在變數 matrix 中。

  • print() 函式用於將 matrix 變數的內容列印到控制檯。

輸出

執行後,您將獲得一個隨機整數矩陣 -

[[1 1 1 0 1]
 [0 1 0 0 0]
 [0 1 0 1 0]
 [0 0 1 0 1]
 [0 0 1 0 1]] 

結論

總之,可以使用 NumPy 庫提供的 "np.random.randint()" 函式在 Python 中生成隨機整數矩陣。

更新於: 2023年4月20日

8K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告