Numpy Left Shift 함수

Beginner

소개

left_shift() 함수는 NumPy 라이브러리의 이진 연산으로, 정수의 비트에 대해 왼쪽 시프트 연산을 수행합니다. 이 튜토리얼에서는 left_shift() 함수의 기본 구문, 매개변수, 반환 값에 대해 안내합니다. 또한 이 함수를 사용하는 몇 가지 예시도 포함합니다.

VM 팁

VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하세요.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수도 있습니다. Jupyter Notebook 의 제한 사항으로 인해 연산의 유효성 검사는 자동화될 수 없습니다.

학습 중 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

NumPy 라이브러리 임포트

먼저, left_shift() 함수를 사용하기 위해 NumPy 라이브러리를 임포트해야 합니다.

import numpy as np

단일 값에 left_shift() 사용하기

left_shift() 함수는 지정된 비트 수만큼 단일 정수 값의 비트를 왼쪽으로 시프트하는 데 사용됩니다. 다음은 예시입니다.

input_num = 40
bit_shift = 2

output = np.left_shift(input_num, bit_shift)

print(f"After shifting {bit_shift} bits to the left, the value is: {output}")

출력:

After shifting 2 bits to the left, the value is: 160

값 배열에 left_shift() 적용하기

left_shift() 함수는 정수 값 배열에도 사용할 수 있습니다. 이 경우, 함수는 배열의 각 요소에 대해 왼쪽 시프트 연산을 수행합니다. 다음은 예시입니다.

input_arr = np.array([2, 8, 10])
bit_shift = np.array([3, 4, 5])

output = np.left_shift(input_arr, bit_shift)

print(f"After shifting the bits to the left, the array is:\n{output}")

출력:

After shifting the bits to the left, the array is:
[ 16 128 320]

left_shift() 함수는 두 배열의 각 요소에 대해 왼쪽 시프트 연산을 적용했습니다.

출력 배열 지정하기

왼쪽 시프트 연산의 결과를 저장할 출력 배열을 지정할 수 있습니다. 출력 배열을 제공하면 함수는 새로운 배열을 할당하는 대신 해당 배열을 업데이트합니다. 출력 배열은 입력 배열과 동일한 모양으로 브로드캐스팅 (broadcasting) 가능해야 합니다. 다음은 예시입니다.

input_arr = np.array([2, 8, 10])
bit_shift = np.array([3, 4, 5])

output = np.zeros_like(input_arr, dtype=np.int64)

np.left_shift(input_arr, bit_shift, out=output)

print(f"After shifting the bits to the left, the output array is:\n{output}")

출력:

After shifting the bits to the left, the output array is:
[ 16 128 320]

출력에 대한 조건 지정

where 매개변수에 조건을 지정하여 출력 배열의 값을 설정할 수도 있습니다. where 매개변수는 입력 배열로 브로드캐스팅 가능한 부울 (boolean) 배열입니다. 다음은 예시입니다.

input_arr = np.array([2, 8, 10])
bit_shift = np.array([3, 4, 5])

output = np.zeros_like(input_arr, dtype=np.int64)
condition = np.array([True, False, True])

np.left_shift(input_arr, bit_shift, out=output, where=condition)

print(f"After shifting the bits to the left, the output array is:\n{output}")

출력:

After shifting the bits to the left, the output array is:
[ 16   8 320]

where 매개변수는 우리가 지정한 조건에 따라 출력 배열의 첫 번째와 세 번째 요소를 설정했습니다.

요약

이 튜토리얼에서는 NumPy 라이브러리의 left_shift() 함수에 대한 개요를 제공했습니다. 기본 구문과 매개변수를 설명한 다음, 이 함수가 반환하는 값을 시연했습니다. 또한 단일 값과 값 배열에 함수를 사용하는 방법, 출력 배열과 출력에 대한 조건을 지정하는 방법에 대한 코드 예제를 제공했습니다.