https://docs.python.org/3/tutorial/stdlib2.html#decimal-floating-point-arithmetic
decimal 모듈 핵심
- Decimal은 사람이 손으로 계산하는 방식과 같은 10진 부동소수 연산을 제공합니다.
- 금융·과학 계산에서 정밀도와 반올림 규칙을 제어하려면 float보다 적합합니다.
오차 없는 예시
from decimal import Decimal, getcontext
#0.70 * 1.05 => 0.735
print(round(Decimal('0.70') * Decimal('1.05'), 2)) #Decimal('0.74')
print(round(0.70 * 1.05, 2)) # 0.73 → 이진 부동소수 오차
print(Decimal('1.00') % Decimal('.10')) #Decimal('0.00')
print(1.00 % 0.10) # 0.09999999999999995
#문자열로 초기화하면 0.70 × 1.05 같은 계산에서 소수점 아래 자릿수를 정확히 유지
print(sum([Decimal('0.1')] * 10) == Decimal('1.0')) # True
print(sum([0.1] * 10) == 1.0) # False- 모듈러 연산과 equality 비교도 기대한 결과가 나와 통화 계산이나 세금 계산에 안전합니다.
정밀도 조절
getcontext().prec = 36 # 정밀도를 36자리로 설정
print(Decimal(1) / Decimal(7)) # Decimal('0.142857142857142857142857142857142857')- getcontext().prec로 필요한 자릿수만큼 정확도를 높일 수 있어 반복소수나 매우 작은 값도 원하는 자리까지 표현 가능합니다.