// Generate continued fraction representation for a number, or turn a // continued fraction back into a number. // See http://mathworld.wolfram.com/ContinuedFraction.html // Generate a continued fraction (as an array) for the number x. // No more than "limit" terms will be produced. Note that this currently // does not check to ensure that precision of the input number is not exceeded. continuedFraction[x, limit] := { r = x result = new array count = 0 while (r != 0) and count < limit { a = floor[r] result.push[a] denom = r - a if denom == 0 break r = 1 / (r - a) count = count + 1 } return result } // Turns an array indicating a continued fraction into a single // fraction indicating its value. continuedFractionToFraction[cf] := { len = length[cf] results = new array frac = 0 for i = len-1 to 1 step -1 frac = 1/(cf@i+frac) return cf@0 + frac } // Turns an array representing a continued fraction back into an array // of fractions. Each fraction in the array shows the results of using more // and more terms from the continued fraction representation. continuedFractionToArray[cf] := { len = length[cf] results = new array for seqlen = 0 to len-1 { frac = 0 for i = seqlen to 1 step -1 frac = 1/(cf@i+frac) results.push[frac+cf@0] } return results } // Return an array which is a series of fractions representing // successively-better approximations to the number x. No more than "limit" // terms will be produced. approximations[x, limit] := continuedFractionToArray[continuedFraction[x,limit]]