Python 標準ライブラリ fractions 有理数
Publish date: 2021-04-04
有理数を扱うためのライブラリfractionsを使うと有理数(分数計算)を簡単に行うことができます。
Fractionの宣言
import fractions
from decimal import Decimal
# fractions.Fraction(numerator=0, denominator=1)
fractions.Fraction() # => Fraction(0, 1) 0/1
fractions.Fraction(6) # => Fraction(6, 1) 6/1
fractions.Fraction(6, 12) # => Fraction(1, 2) 1/2
# fractions.Fraction(other_fraction)
fractions.Fraction(fractions.Fraction(6, 12)) # => Fraction(1, 2) 1/2
# fractions.Fraction(float)
fractions.Fraction(1.25) # => Fraction(5, 4) 5/4
# fractions.Fraction(decimal)
fractions.Fraction(Decimal(0.5)) # => Fraction(1, 2) 1/2
# fractions.Fraction(string)
fractions.Fraction('1.75') # => Fraction(7, 4) 7/4
Fractionのメソッド
numerator 既約分数で表示したときの分子
f = fractions.Fraction(6, 12)
f.numerator # => 1
numerator 既約分数で表示したときの分母
f.denominator # => 2
as_integer_ratio() 分子・分母のタプル
f.as_integer_ratio() # => (1, 2)
# 負号は分子につく
fractions.Fraction(-6, 12).as_integer_ratio() # => (-1, 2)
limit_denominator(max_denominator=1000000) 分母がmax_denominator以下の近い有理数を取得
import math
fractions.Fraction(math.pi).limit_denominator() # => Fraction(3126535, 995207)
fractions.Fraction(math.pi).limit_denominator(100) # => Fraction(311, 99)
fractions.Fraction(1.1).limit_denominator() # => Fraction(11, 10)
floor() 対象より小さい最大の整数
fractions.Fraction(201,100).__floor__() # => 2
math.floor(fractions.Fraction(201,100)) # => 2
ceil() 対象より大きい最小の整数
fractions.Fraction(201,100).__ceil__() # => 3
math.ceil(fractions.Fraction(201,100)) # => 3
round() まるめ
fractions.Fraction(201,100).__round__() # => 2
round(fractions.Fraction(201,100)) # => 2
Fractionへの変換
from_float(flt) float値を有理数に変換
fractions.Fraction.from_float(1.1) # => Fraction(2476979795053773, 2251799813685248)
from_decimal(dec) Decimal値を有理数に変換
fractions.Fraction.from_decimal(Decimal(1.1)) # => Fraction(2476979795053773, 2251799813685248)