Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Mathematica has the ContinuedFraction[] function to give the continued fraction expansion of a rational (or approximation of a real) number. I'm interested in the inverse: is there an efficient way to give an array as a continued fraction expansion and have Mathematica calculate the number it represents?

share|improve this question
13  
There's FromContinedFraction –  Heike Jun 23 '12 at 17:43
1  
Every Mathematica function ref page has a "See also" section and a "More about" section. Looking there on the ContinuedFraction ref page would have given you links to FromContinuedFraction and the overview page "Continued Fractions & Rational Approximations". The tutorial, also mentioned on the same page, contains a discussion of FromContinuedFraction as well. –  Sjoerd C. de Vries Jun 24 '12 at 15:53

1 Answer 1

up vote 14 down vote accepted

As Heike mentions in the comments, FromContinuedFraction[] does what you want:

FromContinuedFraction[{2, 2, 1, 7, 1, 2, 2, 16}]
6784/2891

If FromContinuedFraction[] had not been built-in, however, something like this could be done:

(* backward recursion *)
Fold[#2 + 1/#1 &, Infinity, Reverse[{2, 2, 1, 7, 1, 2, 2, 16}]]
6784/2891

or even

(* forward recursion, matrix multiplication form *)
Divide @@ Last[Fold[{{0, 1}, {1, #2}}.#1 &, {{0, 1}, {1, 0}}, {2, 2, 1, 7, 1, 2, 2, 16}]]

or equivalently

Divide @@ First[Fold[{{#2, 1}, {1, 0}}.#1 &, IdentityMatrix[2], {2, 2, 1, 7, 1, 2, 2, 16}]]

Still another alternative is

(* Lentz-Thompson-Barnett recursion *)
1/(Times @@ Flatten[Rest[FoldList[{#2 + 1/#1[[1]], 1/(#2 + #1[[2]])} &, {1, 0},
                                  {2, 2, 1, 7, 1, 2, 2, 16}]]] - 1)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.