4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

分数の表示(リスト)

Last updated at Posted at 2014-11-06

こんにちは。
Python で Fraction を使えば分数を扱えます。そのような分数の値がリストに入っている時、見栄え良く print 表示出力させるための関数prettyfrac()を作ってみました。Fraction クラスの subclassing で、浮動小数点数のリストの表示出力 prettyfloat()と同様です。

下記例は楕円弧長計算での係数の計算およびその表示出力。

print(prettyfrac(...)) # print pretty fractions
# ==>  [[1, 1/4, 1/64, 1/256], [1/2, -1/16, -1/128], ...]
from fractions import Fraction

def prettyfrac(x):
    def pfform(x):
        num, den = str(x.numerator), str(x.denominator)
        return num + ("" if den == "1" else "/" + den)
    pfclas = type('', (Fraction,), {'__repr__': pfform, '__str__': pfform})
    def pf(x):
        if isinstance(x, Fraction):
            return pfclas(x)
        else:
            return x
    return map_recur(pf, x)

def map_recur(func, args):
    if isinstance(args, list):
        return [map_recur(func, x) for x in args]
    return func(args)

def binom(frac, n):
    b = 1
    while (n > 0):
        b *= frac / n
        frac, n = frac - 1, n - 1
    return b

def coef(k, maxorder):
    k1 = k if k > 0 else 1
    half = Fraction(1, 2) # 1/2
    return map(lambda j: binom(half,j)*binom(half,j+k)/k1, range((maxorder-k)/2+1))

def main():
    maxorder = 6
    print(prettyfrac([coef(k, maxorder) for k in range(maxorder+1)]))

# ==>  [[1, 1/4, 1/64, 1/256], [1/2, -1/16, -1/128], [-1/16, 1/64, 5/2048], [1/48, -5/768], [-5/512, 7/2048], [7/1280], [-7/2048]]
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?