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

파이썬 NumPy로 float 데이터 타입의 머신 한계 정보 조회하기

파이썬에서 float 타입의 머신 한계(machine limits) 정보를 확인하려면 NumPy의 numpy.finfo() 메서드를 사용하면 됩니다. 이 메서드의 첫 번째 매개변수는 float 값으로, 정보를 조회하고자 하는 float 데이터 타입의 종류를 지정합니다.

반환된 객체에서 min 속성은 해당 dtype이 표현할 수 있는 최솟값을, max 속성은 최댓값을 나타냅니다.

실행 단계

1단계: 라이브러리 임포트

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

import numpy as np

2단계: float16 타입 인스턴스로 확인하기

float16 타입의 인스턴스를 전달하여 최솟값과 최댓값을 확인합니다.

a = np.finfo(np.float16(12.5))
print("Minimum of float16 type...\n", a.min)
print("Maximum of float16 type...\n", a.max)

3단계: float32 타입 인스턴스로 확인하기

같은 방식으로 float32 타입도 확인할 수 있습니다.

b = np.finfo(np.float32(30.5))
print("\nMinimum of float32 type...\n", b.min)
print("Maximum of float32 type...\n", b.max)

4단계: float64 타입 인스턴스로 확인하기

마지막으로 float64 타입의 머신 한계를 확인합니다.

c = np.finfo(np.float64(55.9))
print("\nMinimum of float64 type...\n", c.min)
print("Maximum of float64 type...\n", c.max)

전체 예제 코드

import numpy as np

# 파이썬 NumPy의 numpy.finfo() 메서드로 float 타입의 머신 한계 정보를 조회합니다.
# 첫 번째 매개변수는 float 값으로, 정보를 얻을 float 데이터 타입을 지정합니다.

# float16 타입 인스턴스로 확인
# min은 해당 dtype의 최솟값, max는 최댓값입니다.
a = np.finfo(np.float16(12.5))
print("Minimum of float16 type...\n", a.min)
print("Maximum of float16 type...\n", a.max)

# float32 타입 인스턴스로 확인
b = np.finfo(np.float32(30.5))
print("\nMinimum of float32 type...\n", b.min)
print("Maximum of float32 type...\n", b.max)

# float64 타입 인스턴스로 확인
c = np.finfo(np.float64(55.9))
print("\nMinimum of float64 type...\n", c.min)
print("Maximum of float64 type...\n", c.max)

출력 결과

Minimum of float16 type...
-65500.0
Maximum of float16 type...
65500.0

Minimum of float32 type...
-3.4028235e+38
Maximum of float32 type...
3.4028235e+38

Minimum of float64 type...
-1.7976931348623157e+308
Maximum of float64 type...
1.7976931348623157e+308

정리

np.finfo()에 float 타입의 인스턴스를 전달하면 해당 데이터 타입이 표현 가능한 최솟값과 최댓값을 손쉽게 확인할 수 있습니다. float16은 약 ±65,500까지, float32는 약 ±3.4×10³⁸까지, float64는 약 ±1.79×10³⁰⁸까지 표현할 수 있으며, 이는 수치 연산 시 오버플로우 여부를 판단하는 데 유용하게 활용됩니다.