Python 라이브러리 - decimal

공식 문서

source code

decimal

decimal.Decimal

decimal.Decimal은 숫자를 10진수로 처리해 정확한 소수점 자릿수를 표현할 때 사용하는 모듈입니다.

print(0.1 * 3)  # 0.30000000000000004
print(1.2 - 0.1)# 1.0999999999999999
print(0.1 * 0.1)# 0.010000000000000002

위의 예시는 python에서 볼 수 있는 이상한 연산 결과의 예입니다. 이진수 기반의 python float 연산은 위처럼 미세한 오차가 발생할 수 있습니다.

print(0.1 * 3 == 0.3)   # False

import math
print(math.isclose(0.1 * 3, 0.3))   # True

그래서 같은지를 비교할 때 == 연사낮 대신 두 값이 가까운지를 확인하는 math.isclose() 함수를 사용할 수 있습니다.

print(math.isclose(0.1 * 3, 0.3000000001))  # True

하지만 위의 예시처럼 math.isclose()는 가까운 값이면 True를 반환하기 때문에 완전한 해결이 될 수는 없습니다.

그러므로 decimal.Decimal을 사용해 문제를 해결해야 합니다.

from decimal import Decimal


result = Decimal('0.1') * 3
print(result)       # 0.3
print(type(result)) # <class 'decimal.Decimal'>

위의 예시처럼 인수('0.1')는 문자열이어야 합니다.
또한 결과값은 Decimal 자료형이고 float 자료형으로 형변환을 할 수 있습니다.

result = float(result)
print(result)       # 0.3
print(type(result)) # <class 'float'>

참고로 Decimal 객체는 위의 예시처럼 정수 연산은 가능하지만, 실수 연산은 불가능합니다.

# result = Decimal('1.1') * 3.0
# TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'
result = float(Decimal('1.1') * Decimal(3.0))
print(result)       # 3.3

Decimal 사용하는 경우

Decimal은 정확성을 향상하고자 고정 소수를 사용하기에 메모리를 많이 차지합니다. 그래서 모든 float 연산을 Decimal로 바꾸는 것은 바람직하지 않습니다. 그래서 Decimal은 보통 금융권, 재무/회계 관련 프로그램을 작성할 때 사용하는 것이 좋습니다.

 

 

 

 

 

'Python > Python' 카테고리의 다른 글

Python 라이브러리 - random  (0) 2023.05.17
Python 라이브러리 - fractions  (0) 2023.05.17
Python 라이브러리 - math  (0) 2023.05.16
Python 라이브러리 - enum  (0) 2023.05.16
Python 라이브러리 - pprint  (0) 2023.05.16