Continued fractions

The following Javascript gives the continued fraction expansion of a numeric value or an expression.
The successive terms of the CF are in [ ], ε = x - P/Q

value

Syntax :
Operations +, -, *, /, %, parenthesis ( ).
x%y is x modulo y (remainder of division of x by |y|, with the sign of x). x%1 is the fractional part, alias frac(x)
Note : the x^y operation must be written pow(x, y). "x^y" meaning the binary exclusive or (rejected) !
Constants : pi = π = 3.1415..., e = 2.71828...
Numbers as signed integers or floating point values [+/-]xxx[.yyy][E[+/-]nn], ex : 3.14, 1.54E-4, -12345 ...
(note that 'e' is understood as constant e, you must use capital E in numbers)
log( ) = base 10 logarithm, ln( ) = natural, base e logarithm, log2( ) = base 2 logarithm
exp(x) = ex, pow(x, y) = xy, sqrt(x) = x
sin( ), cos( ), tan( ), asin( ), acos( ), atan( ), abs(x), max(x, y), min(x, y)
ceil(x) is the smallest relative integer (in Z) ≥ x,
floor(x) the largest relative integer ≤x
round(x) the nearest relative integer to x

Because of the limited accuracy with floating point numbers in Javascript, the last convergents (with large P, Q) are not granted.
An accuracy calculation should be done in a case per case basis, considering the Floating point accuracy is ≈ 10-16 in Javascript.

Specific continued fractions

Rational numbers : The corresponding continued fractions are finite, see the Euclides algorithm
Quadratic irrationals : periodic continued fraction, see the PQA algorithm
Number e = [2,1,2,1,1,4,1,...,1,2n,1,...]
ln(1 + x) = x/(1 + x/(2 + x/(3 + 4x/(4 + 4x/(5 + 9x/(6 + 9x/(7 + ...
This is not an unitary continued fraction, but allows to get the exact convergents from the iterative formula :
P[i] = a[i]P[i-1] + b[i]P[i-2], Q[i] = a[i]P[i-1] + b[i]Q[i-2]
a[i] = i+1 = 1,2,3,4,5,6,...
b[0] = x, b[i] = floor((i+1)/2)²x = x, x, x, 4x, 4x, 9x, 9x, 16x, 16x, 25x, 25x,...
in the same way as for convergents of a unitary CF, where all b[i] = 1
The same method gives the exact convergents for π = 4/(1 + 1/(2 + 3²/(2 + 5²/(2 + 7²/(2 + ...

 

Home Arithmetic Geometric Misc Topics Scripts Games Exercices Mail Version Française Previous topic Next topic