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
广告