Pythonのfractionsモジュールで分数(有理数)計算をマスター【完全ガイド】
Pythonのfractionsモジュールを使えば、浮動小数点数の誤差を避けて正確な分数計算が可能です。この記事では、fractionsモジュールの使い方を実践的なサンプルコードと共に詳しく解説します。
目次
fractionsモジュールとは
fractionsモジュールは、分数(有理数)を正確に表現・計算するためのPython標準ライブラリです。浮動小数点数では表現できない正確な分数計算が可能になります。
浮動小数点数の問題点
# 浮動小数点数の誤差例
result = 0.1 + 0.2
print(result) # 0.30000000000000004(期待値: 0.3)
# 分数での正確な計算
from fractions import Fraction
frac_result = Fraction(1, 10) + Fraction(2, 10)
print(frac_result) # 3/10
Fractionオブジェクトの作成
基本的な作成方法
from fractions import Fraction
# 整数から分数を作成
f1 = Fraction(3) # 3/1
f2 = Fraction(3, 4) # 3/4
f3 = Fraction(-2, 5) # -2/5
# 文字列から分数を作成
f4 = Fraction('1/2') # 1/2
f5 = Fraction('0.25') # 1/4
f6 = Fraction('3.14') # 157/50
自動約分機能
from fractions import Fraction
# 自動的に約分される
f1 = Fraction(6, 9) # 2/3
f2 = Fraction(15, 25) # 3/5
f3 = Fraction(100, 200) # 1/2
print(f1) # 2/3
print(f2) # 3/5
print(f3) # 1/2
分数の四則演算
加算・減算
from fractions import Fraction
f1 = Fraction(1, 3)
f2 = Fraction(1, 6)
# 加算
sum_result = f1 + f2 # 1/3 + 1/6 = 1/2
print(sum_result) # 1/2
# 減算
diff_result = f1 - f2 # 1/3 - 1/6 = 1/6
print(diff_result) # 1/6
乗算・除算
from fractions import Fraction
f1 = Fraction(2, 3)
f2 = Fraction(3, 4)
# 乗算
product = f1 * f2 # 2/3 * 3/4 = 1/2
print(product) # 1/2
# 除算
quotient = f1 / f2 # 2/3 ÷ 3/4 = 8/9
print(quotient) # 8/9
べき乗演算
from fractions import Fraction
f = Fraction(2, 3)
# べき乗
power_result = f ** 2 # (2/3)^2 = 4/9
print(power_result) # 4/9
# 負のべき乗(逆数)
inverse = f ** -1 # (2/3)^-1 = 3/2
print(inverse) # 3/2
分数と他の数値型との演算
整数との演算
from fractions import Fraction
f = Fraction(3, 4)
# 整数との加算
result1 = f + 2 # 3/4 + 2 = 11/4
print(result1) # 11/4
# 整数との乗算
result2 = f * 3 # 3/4 * 3 = 9/4
print(result2) # 9/4
浮動小数点数との演算
from fractions import Fraction
f = Fraction(1, 2)
# 浮動小数点数との演算(結果は浮動小数点数)
result = f + 0.25 # 0.75
print(result) # 0.75
print(type(result)) # <class 'float'>
分数のプロパティとメソッド
基本プロパティ
from fractions import Fraction
f = Fraction(3, 4)
# 分子と分母の取得
numerator = f.numerator # 3
denominator = f.denominator # 4
print(f"分子: {numerator}")
print(f"分母: {denominator}")
limit_denominator()メソッド
from fractions import Fraction
import math
# 円周率の近似分数
pi_approx = Fraction(math.pi).limit_denominator(100)
print(pi_approx) # 22/7
# より精密な近似
pi_precise = Fraction(math.pi).limit_denominator(1000)
print(pi_precise) # 355/113
分数の比較演算
大小比較
from fractions import Fraction
f1 = Fraction(1, 2)
f2 = Fraction(3, 4)
f3 = Fraction(2, 4) # 1/2と同じ
# 比較演算
print(f1 < f2) # True
print(f1 == f3) # True
print(f2 > f1) # True
ソート
from fractions import Fraction
fractions_list = [
Fraction(3, 4),
Fraction(1, 2),
Fraction(5, 6),
Fraction(1, 3)
]
# ソート
sorted_fractions = sorted(fractions_list)
print(sorted_fractions)
# [Fraction(1, 3), Fraction(1, 2), Fraction(3, 4), Fraction(5, 6)]
実践的な応用例
分数の平均値計算
from fractions import Fraction
def fraction_average(*fractions):
total = sum(fractions)
return total / len(fractions)
# 分数のリストの平均
fracs = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4)]
avg = fraction_average(*fracs)
print(avg) # 13/36
連分数の計算
from fractions import Fraction
def continued_fraction_to_fraction(cf_list):
if not cf_list:
return Fraction(0)
result = Fraction(cf_list[-1])
for i in range(len(cf_list) - 2, -1, -1):
result = Fraction(cf_list[i]) + 1/result
return result
# 黄金比の連分数近似 [1; 1, 1, 1, 1]
golden_ratio = continued_fraction_to_fraction([1, 1, 1, 1, 1])
print(golden_ratio) # 8/5
分数から小数への変換制御
from fractions import Fraction
from decimal import Decimal, getcontext
# 精度を設定
getcontext().prec = 28
f = Fraction(1, 3)
# 浮動小数点数への変換
float_val = float(f)
print(float_val) # 0.3333333333333333
# Decimalへの変換(高精度)
decimal_val = Decimal(f.numerator) / Decimal(f.denominator)
print(decimal_val) # 0.3333333333333333333333333333
パフォーマンスと注意点
メモリ使用量
from fractions import Fraction
import sys
f1 = 0.5 # float
f2 = Fraction(1, 2) # Fraction
print(f"float size: {sys.getsizeof(f1)}") # 24 bytes
print(f"Fraction size: {sys.getsizeof(f2)}") # 32 bytes
演算速度の比較
from fractions import Fraction
import time
# float演算
start = time.time()
result_float = 0.0
for i in range(10000):
result_float += 0.1
end = time.time()
print(f"Float時間: {end - start:.6f}秒")
# Fraction演算
start = time.time()
result_frac = Fraction(0)
frac_tenth = Fraction(1, 10)
for i in range(10000):
result_frac += frac_tenth
end = time.time()
print(f"Fraction時間: {end - start:.6f}秒")
数学ライブラリとの連携
mathモジュールとの組み合わせ
from fractions import Fraction
import math
# 三角関数の結果を分数で近似
angle_frac = Fraction(1, 4) # π/4の代わり
sin_approx = Fraction(math.sin(float(angle_frac * math.pi))).limit_denominator(100)
print(sin_approx) # 71/100 (≈ 0.71)
まとめ
Pythonのfractionsモジュールは以下の場面で特に有用です:
- 金融計算での正確な小数点計算
- 数学的な証明での厳密な分数演算
- 教育用途での分数の視覚化
- 科学計算での誤差の最小化
浮動小数点数では表現できない正確な分数計算が必要な場合は、ぜひfractionsモジュールを活用してください。パフォーマンスが重要でない場面では、その精度の高さが大きな利点となります。
■らくらくPython塾 – 読むだけでマスター
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座

