Hello.
You can use Fraction in Python to work with fractions. When such a fractional value is in the list, I made a function `prettyfrac ()`
to display and output a nice print. In the subclassing of the Fraction class, it is similar to Display output of floating point number list prettyfloat ().
The following example is the calculation of the coefficient and its display output in Calculation of elliptical arc length.
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]]
Recommended Posts