NumPy 右移() 函式



NumPy 的right_shift()函式用於對陣列的元素執行按位右移運算。此函式將輸入陣列中每個元素的位向右移動指定數量的位置。每當一位移動時,在左側插入一個零。

此函式可以接受陣列或標量作為輸入,以及要移動的位置數。結果是一個與輸入形狀相同的陣列,其中包含移位後的值。它通常用於涉及按位操作的任務,例如二進位制算術或數字訊號處理。

語法

以下是 Numpy right_shift() 函式的語法:

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

引數

Numpy right_shift() 函式接受以下引數:

  • x1: 應用右移運算的輸入值。
  • x2: 要應用的右移位置數。
  • out(ndarray, None 或 ndarray 和 None 的元組,可選):儲存結果的位置。
  • where(array_like,可選):這是必須應用右移運算的條件。
  • **kwargs: 引數(如 casting、order、dtype、subok)是其他關鍵字引數,可根據需要使用。

返回值

此函式返回一個數組,其中每個元素都是將輸入值中相應元素的位向右移動 shift 指定的位置數的結果。

示例 1

以下是 Numpy right_shift() 函式的基本示例,其中將整數的位向右移動指定數量的位置,有效地將數字除以 2 的冪:

import numpy as np

# Define an integer
number = 16  # Binary: 00010000

# Define the number of positions to shift
shift_positions = 2

# Perform the right shift operation
result = np.right_shift(number, shift_positions)

print('Original number:', number)
print('Binary representation:', np.binary_repr(number, width=8))
print(f'Right shift by {shift_positions} positions results in:', result)
print('Binary representation after shift:', np.binary_repr(result, width=8))  

以下是應用於整數的right_shift() 函式的輸出:

Original number: 16
Binary representation: 00010000
Right shift by 2 positions results in: 4
Binary representation after shift: 00000100

示例 2

在處理按位移位運算時,通常不支援負移位值。嘗試使用負移位值通常會導致錯誤或未定義的行為,具體取決於實現和特定的操作。以下是它的示例:

import numpy as np

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

# Define a negative number of positions to shift
negative_shift_positions = -2

try:
    # Attempt to perform the right shift operation with a negative shift value
    result = np.right_shift(array, negative_shift_positions)
    print('Result with negative shift value:', result)
except ValueError as e:
    print('Error:', e)

以下是負右移的輸出:

Result with negative shift value: [0 0 0 0]

示例 3

這是使用right_shift() 函式執行位右移運算的另一個示例:

import numpy as np

# Create a One-Dimensional array
arr = np.array([56, 87, 23, 92, 81, 98, 45, 98])

# Displaying our array
print("Array:", arr)

# Get the datatype
print("Array datatype:", arr.dtype)

# Get the dimensions of the Array
print("Array Dimensions:", arr.ndim)

# Get the shape of the Array
print("Our Array Shape:", arr.shape)

# Get the number of elements of the Array
print("Elements in the Array:", arr.size)

# The count of right shift
valRight = 3
# To shift the bits of an integer to the right, use the numpy.right_shift() method in Python Numpy
result = np.right_shift(arr, valRight)

# Display the result of the right shift operation
print("Result (right shift):", result)

以下是右移的輸出:

Array: [56 87 23 92 81 98 45 98]
Array datatype: int64
Array Dimensions: 1
Our Array Shape: (8,)
Elements in the Array: 8
Result (right shift): [ 7 10  2 11 10 12  5 12]
numpy_binary_operators.htm
廣告