Big Data/Analytics Zone is brought to you in partnership with:

John Cook is an applied mathematician working in Houston, Texas. His career has been a blend of research, software development, consulting, and management. John is a DZone MVB and is not an employee of DZone and has posted 171 posts at DZone. You can read more from them at their website. View Full User Profile

# Continued Fractions with Sage

02.01.2013
| 1442 views |

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 erather than the default precision.

Published at DZone with permission of John Cook, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

"Starting from scratch" is seductive but disease ridden