Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

NumPy result_type() – 타입 승격 규칙을 적용한 결과 데이터 타입 구하기

numpy.result_type() 메서드는 인수에 NumPy의 타입 승격(type promotion) 규칙을 적용한 결과로 결정되는 데이터 타입을 반환합니다. 첫 번째 매개변수에는 결과 타입을 확인하고자 하는 연산의 피연산자(operand)를 전달합니다.

NumPy의 타입 승격은 C++와 같은 프로그래밍 언어의 규칙과 유사하게 동작하지만, 몇 가지 사소한 차이점이 있습니다. 특히 스칼라와 배열이 함께 사용될 경우 배열의 dtype이 우선하며, 동시에 스칼라의 실제 값도 함께 고려된다는 점이 특징입니다.

구현 단계

먼저 필요한 라이브러리를 임포트합니다.

import numpy as np

numpy.result_type() 메서드는 인수에 NumPy 타입 승격 규칙을 적용하여 얻은 결과 타입을 반환합니다.

print("Using the result_type() method in Numpy\n")
print("Result...",np.result_type(2, np.arange(4,dtype='i1')))
print("Result...",np.result_type(5, 8))
print("Result...",np.result_type('i4', 'c8'))
print("Result...",np.result_type(3.8, 8))
print("Result...",np.result_type(5, 20.7))
print("Result...",np.result_type(-8, 20.7))
print("Result...",np.result_type(10.0, -4))

전체 예제

import numpy as np
# numpy.result_type() 메서드는 인수에 NumPy 타입 승격 규칙을
# 적용한 결과로 결정되는 데이터 타입을 반환합니다.
# 첫 번째 매개변수는 결과 타입이 필요한 연산의 피연산자입니다.
print("Using the result_type() method in Numpy\n")

print("Result...",np.result_type(2, np.arange(4,dtype='i1')))
print("Result...",np.result_type(5, 8))
print("Result...",np.result_type('i4', 'c8'))
print("Result...",np.result_type(3.8, 8))
print("Result...",np.result_type(5, 20.7))
print("Result...",np.result_type(-8, 20.7))
print("Result...",np.result_type(10.0, -4))

실행 결과

Using the result_type() method in Numpy

Result... int8
Result... int64
Result... complex128
Result... float64
Result... float64
Result... float64
Result... float64

결과 해석

각 호출의 결과를 살펴보면 다음과 같습니다.

  • int8: 스칼라 2와 dtype이 'i1'(int8)인 배열을 함께 전달했기 때문에 배열의 타입인 int8이 우선 적용되었습니다.
  • int64: 정수 스칼라 두 개(5, 8)의 조합은 시스템 기본 정수 타입인 int64로 승격됩니다.
  • complex128: 정수 타입 'i4'와 복소수 타입 'c8'이 만나면 더 큰 표현 범위를 가진 complex128로 승격됩니다.
  • float64: 부동소수점 값이 포함된 모든 조합(3.8과 8, 5와 20.7, -8과 20.7, 10.0과 -4)은 float64로 승격됩니다.

이처럼 result_type() 메서드를 활용하면 연산 수행 전에 결과 배열의 dtype을 미리 예측할 수 있어, 메모리 사용량 최적화나 dtype 불일치로 인한 오류 방지에 유용합니다.