# Continued Fractions with Sage

# Continued Fractions with Sage

Join the DZone community and get the full member experience.

Join For FreeHortonworks Sandbox for HDP and HDF is your chance to get started on learning, developing, testing and trying out new features. Each download comes preconfigured with interactive tutorials, sample data and developments from the Apache community.

My previous post looked at continued fractions and rational approximations for *e* and gave a little Python code. I found out later there’s a more direct way to do this in Python using Sage.

At its simplest, the function `continued_fraction`

takes a real number and returns a truncated continued fraction representation. For example, `continued_fraction(e)`

returns

[2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1]

Optionally, you can also specify the number of bits of precision in the real argument and the number of terms desired.

By calling the `convergents`

method on the return value of `continued_fraction(e)`

you can find a sequence of rational approximations based on the continued fraction. For example,

print continued_fraction(e).convergents()

produces

[2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, 2721/1001, 23225/8544, 25946/9545, 49171/18089, 517656/190435, 566827/208524, 1084483/398959, 13580623/4996032, 14665106/5394991, 28245729/10391023].

To get higher precision output, you need higher precision input. For example, you could pass in

RealField(200)(e)

rather than simply `e`

to tell Sage that you’d like to use the 200-bit representation of *e*rather than the default precision.

Hortonworks Community Connection (HCC) is an online collaboration destination for developers, DevOps, customers and partners to get answers to questions, collaborate on technical articles and share code examples from GitHub. Join the discussion.

Published at DZone with permission of John Cook , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

## {{ parent.title || parent.header.title}}

## {{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}