NumPy의 min_scalar_type() 메서드는 주어진 값이 저장될 수 있는 가장 작은 크기의 데이터 타입을 찾아주는 유용한 함수입니다. 첫 번째 매개변수에는 최소 데이터 타입을 확인하고자 하는 값을 전달합니다.
이 메서드는 스칼라(scalar) 값에 대해서는 해당 값을 담을 수 있는 가장 작은 크기와 가장 작은 스칼라 종류를 가진 데이터 타입을 반환하며, 비스칼라(non-scalar) 배열에 대해서는 벡터의 dtype을 그대로 수정 없이 반환합니다.
또한 중요한 규칙이 있습니다. 부동 소수점 값은 정수로 강등되지 않고, 복소수 값은 부동 소수점으로 강등되지 않습니다. 즉, 원래 값의 성격은 유지된 채 최소한의 타입만 찾아줍니다.
사용 단계
1단계: 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import numpy as np
2단계: min_scalar_type() 메서드 호출
최소 데이터 타입을 확인할 값을 첫 번째 매개변수로 전달하여 메서드를 호출합니다.
print("Using the min_scalar() method in Numpy\n")
print("Result...",np.min_scalar_type(np.arange(4,dtype='f8')))
print("Result...",np.min_scalar_type(np.arange(38.9, dtype = 'f8')))
print("Result...",np.min_scalar_type(np.array(6.5e100, np.float64)))
print("Result...",np.min_scalar_type(np.array(280, 'i1')))
print("Result...",np.min_scalar_type(np.array(80, 'u1')))
print("Result...",np.min_scalar_type(np.array(300.7, np.float32)))
print("Result...",np.min_scalar_type(np.array(120.6, np.float64)))
print("Result...",np.min_scalar_type(np.array(7.2e100, np.float32)))
print("Result...",np.min_scalar_type(np.array(6.5e100, np.float64)))전체 예제 코드
import numpy as np
# numpy.min_scalar_type() 메서드는 최소 데이터 타입을 찾습니다.
# 첫 번째 매개변수는 최소 데이터 타입을 확인할 값입니다.
print("Using the min_scalar() method in Numpy\n")
print("Result...",np.min_scalar_type(np.arange(4,dtype='f8')))
print("Result...",np.min_scalar_type(np.arange(38.9, dtype = 'f8')))
print("Result...",np.min_scalar_type(np.array(6.5e100, np.float64)))
print("Result...",np.min_scalar_type(np.array(280, 'i1')))
print("Result...",np.min_scalar_type(np.array(80, 'u1')))
print("Result...",np.min_scalar_type(np.array(300.7, np.float32)))
print("Result...",np.min_scalar_type(np.array(120.6, np.float64)))
print("Result...",np.min_scalar_type(np.array(7.2e100, np.float32)))
print("Result...",np.min_scalar_type(np.array(6.5e100, np.float64)))출력 결과
Using the min_scalar() method in Numpy Result... float64 Result... float64 Result... float64 Result... uint8 Result... uint8 Result... float16 Result... float16 Result... float16 Result... float64
결과 해석
출력 결과를 살펴보면 몇 가지 흥미로운 동작을 확인할 수 있습니다.
- 배열 입력:
np.arange(4, dtype='f8')처럼 비스칼라 배열을 전달하면 원본 dtype인float64가 그대로 반환됩니다. - 정수 값: 280과 80 같은 정수는 모두
uint8(부호 없는 8비트 정수)로 판별됩니다. - 부동 소수점 값: 300.7과 120.6은
float16으로 반환되는데, 이는 부동 소수점 값이 정수로 강등되지 않기 때문입니다. - 매우 큰 실수: 6.5e100처럼 지수 표현의 큰 값은
float16이나float32로 표현할 수 없으므로float64가 반환됩니다.
이처럼 min_scalar_type()은 메모리를 절약하면서도 값을 안전하게 저장할 수 있는 최적의 데이터 타입을 결정할 때 매우 유용하게 활용됩니다.