Python 라이브러리 - fractions

공식 문서

source code 링크

fractions

fractions는 유리수를 계산할 때 사용하는 모듈입니다.

result = 1/5 + 2/5
print(result)   # 0.6000000000000001

위의 예시는 python에서 볼 수 있는 이상한 연산 결과의 예입니다. 원래 계산 결과는 0.6(3/5)이여야 하지만 이진수 기반의 python float 연산은 위처럼 미세한 오차가 발생할 수 있습니다.

python에서 유리수 연산을 정확하게 하려면 fractions.Fraction을 사용해야 합니다.

유리수는 Fraction(분자, 분모) 형태 또는 Fraction('분자/분모') 형태로 만들 수 있습니다.

from fractions import Fraction

result_1 = Fraction(1, 5)
result_2 = Fraction('1/5')
print(result_1, result_2, result_1 == result_2) # 1/5 1/5 True

분자의 값은 numerator로, 분모의 값은 denominator 알 수 있습니다.

print(result_1.numerator)   # 1
print(result_1.denominator) # 5

맨 처음 예시는 fractions를 사용해서 아래처럼 계산할 수 있습니다.

result = float(Fraction(1, 5) + Fraction(2, 5))
print(result)   # 0.6

 

 

 

 

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

Python 라이브러리 - statistics  (0) 2023.05.17
Python 라이브러리 - random  (0) 2023.05.17
Python 라이브러리 - decimal  (0) 2023.05.16
Python 라이브러리 - math  (0) 2023.05.16
Python 라이브러리 - enum  (0) 2023.05.16