Comment #12 on issue 55 by
smi...@gmail.com: implement continued fractions
http://code.google.com/p/mpmath/issues/detail?id=55
def continued_fraction(r):
"""Calculate the continued fraction of the given Rational
or the Rational from the given continued fraction.
continued fractions are in the form [a0, a1, a2, a3, ...]
for a0 + 1/(a1 + 1/(a2 + 1/(a3 + ...
Any other input will raise a ValueError
Examples
========
>>> from sympy import Rational
>>> continued_fraction(Rational(3,14))
[0, 4, 1, 2]
>>> continued_fraction(_)
3/14
>>> continued_fraction(2 + _)
[2, 4, 1, 2]
"""
if isinstance(r, Rational):
p, q = r.p, r.q
rv = []
while q:
n = p // q
rv.append(int(n))
q, p = p - q*n, q
return rv
elif isinstance(r, list):
cf = r or [S.Zero]
rv = Integer(cf.pop())
while cf:
rv = Integer(cf.pop()) + S.One/rv
return rv
else:
raise ValueError