NumPy 的按位右移函式()



numpy 的 **bitwise_right_shift()** 函式用於對輸入陣列的每個元素執行按位右移運算。

此函式將每個整數的位向右移動指定的位數,有效地將數字除以 2 的冪。

對於正整數,此函式的結果為整數除法;對於有符號整數,它透過執行算術移位來保持符號。

此函式處理各種整數型別的陣列,並返回具有相同形狀和型別的陣列。它等效於在 Python 中使用右移運算子 **>>**。

語法

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

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

引數

NumPy **bitwise_right_shift()** 函式採用以下引數:

  • **x1:** 應用右移的輸入值。
  • **x2:** 輸入值 x1 右移的位數。
  • **out(ndarray, None 或 ndarray 和 None 的元組,可選):** 儲存結果的位置。
  • **where(array_like, 可選):** 此引數是廣播到輸入的條件。
  • **kwargs:** 引數例如 casting, order, dtype 和 subok 是附加的關鍵字引數,可根據需要使用。

返回值

此函式返回一個數組,其中每個元素都已右移。

示例 1

以下是 NumPy **bitwise_right_shift()** 函式的基本示例,其中對整數 18 執行按位右移 2 位:

import numpy as np

# Define the integer and the shift amount
x = 18
shift = 2

# Perform the bitwise right shift operation
result = np.right_shift(x, shift)
print(result)    

以下是將 **bitwise_right_shift()** 函式應用於整數 18 的輸出:

4

示例 2

當使用移位值陣列執行按位右移時,NumPy 允許我們根據另一個數組指定的不同位數來移動輸入陣列的每個元素。以下是一個示例:

import numpy as np

# Define the input array and the array of shift values
x = np.array([16, 32, 64])
shift_values = np.array([1, 2, 3])

# Perform the bitwise right shift operation
result = np.right_shift(x, shift_values)
print(result)  

以下是按位右移的輸出:

[8 8 8]
numpy_binary_operators.htm
廣告