Code: Select all

```
from fractions import Fraction
def contfrac_to_frac(cfr):
if len(cfr) == 0:
return Fraction(0)
elif len(cfr) == 1:
return Fraction(cfr[0])
else:
return Fraction(cfr[0]) + 1 / contfrac_to_frac(cfr[1:])
def frac_to_contfrac(frac):
frac = Fraction(frac)
if frac.denominator == 1:
return [frac.numerator]
else:
ipart, fpart = divmod(frac, 1)
return [int(ipart)] + frac_to_contfrac(1 / fpart)
```

Note that since all finite float values are rational, they will all have a finite continued fraction representation.

Some interesting "irrational" values are:

Code: Select all

```
>>> frac_to_contfrac(math.e)
[2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1, 11, 1, 1, 1, 11, 5, 1, 1, 2, 1, 4, 2, 1, 1, 9, 17, 3]
>>> frac_to_contfrac(math.sqrt(2))
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 7, 1, 2, 33, 2, 7, 5, 2, 1, 1, 16, 2]
>>> frac_to_contfrac((1 + math.sqrt(5)) / 2)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 7, 1, 5, 5, 1, 1, 2, 4, 1, 1, 10, 1, 2, 1, 8]
```