NumPy 左移() 函式



NumPy 的left_shift()函式用於對陣列元素執行按位左移運算。

當給出兩個陣列或一個數組和一個標量時,它會將第一個陣列中每個元素的位向左移動第二個陣列或標量中指定的位數。結果相當於將陣列元素乘以 2**shift。

  • 此函式透過允許對不同形狀的陣列進行運算來支援廣播。它在低階資料操作(如二進位制編碼、影像處理和需要精確位控制的操作)中很有用。
  • 在按位運算的上下文中,負移位值通常與右移運算一起使用,其中位向右移動。
  • 在左移運算中,負值沒有有意義的解釋,行為可能不一致或未定義。

語法

以下是 NumPy left_shift() 函式的語法:

numpy.left_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])

引數

以下是 NumPy left_shift() 函式的引數:

  • x1(array_like): 對其執行左移運算的輸入陣列。
  • x2(array_like 或 int): 將 x1 的每個元素左移的位數。它可以是單個整數或與 x1 形狀相同的陣列。
  • out(可選): 這是儲存結果的可選輸出陣列。
  • where(可選): 用於確定應執行移位運算的位置的條件。在此條件為 True 的情況下計算結果。
  • **kwargs: 引數 casting、order、dtype、subok 屬於附加關鍵字引數。

返回值

該函式返回一個數組,其中每個元素都是左移原始陣列對應位的位的結果。

示例 1

以下是 NumPy left_shift() 函式的基本示例,其中陣列的單個整數被左移:

import numpy as np
# Shift the bits of the integer 5 to the left by 1 position
result = np.left_shift(5, 1)
print(result)  

以下是 left_shift() 函式的輸出:

10

示例 2

我們可以透過將每個元素的位向左移動指定的位數來對陣列的所有元素執行統一的標量移位。在此示例中,我們將陣列左移 3 位:

import numpy as np

# Define an array of integers
array = np.array([5, 10, 15, 20])

# Define the scalar shift value
shift = 3

# Perform the left shift operation
result = np.left_shift(array, shift)

print("Original array:", array)
print("Shifted array:", result)

以下是上述示例的輸出:

Original array: [ 5 10 15 20]
Shifted array: [ 40  80 120 160]

示例 3

以下示例對數字 10 執行左移兩位,並顯示結果,包括原始值和移位值的二進位制表示:

import numpy as np 

print('Left shift of 10 by two positions:') 
print(np.left_shift(10, 2))  

print('Binary representation of 10:') 
print(np.binary_repr(10, width=8)) 

print('Binary representation of 40:') 
print(np.binary_repr(40, width=8))  

以下是上述示例的輸出:

Left shift of 10 by two positions:
40
Binary representation of 10:
00001010
Binary representation of 40:
00101000

示例 2

在此示例中,left_shift() 不會以標準方式處理負移位,並且左移的結果可能與預期不符。相反,結果通常沒有意義,並且可能預設為與在此示例中看到的值相同的值:

import numpy as np

# Define an array of integers
array = np.array([16, 32, 64, 128])

# Define the array of shift values, including negative values
shifts = np.array([-1, -2, -3, -4])

# Perform the left shift operation
result = np.left_shift(array, shifts)

print('Original array:', array)
print('Shift values:', shifts)
print('Shifted array:', result) 

以下是上述示例的輸出:

Original array: [ 16  32  64 128]
Shift values: [-1 -2 -3 -4]
Shifted array: [0 0 0 0]
numpy_binary_operators.htm
廣告