Using Continued fractions , it is possible to efficiently create (finite or infinite) a sequence of fractions h n / k n that are arbitrary good approximations to a given real number x.
x - , h n/k n == x. x , h n/k n, n = 0, 1, 2,... x.
( ),
" " .
JavaScript ( C), JavaScript. , , . , , .
function getlowestfraction(x0) {
var eps = 1.0E-15;
var h, h1, h2, k, k1, k2, a, x;
x = x0;
a = Math.floor(x);
h1 = 1;
k1 = 0;
h = a;
k = 1;
while (x-a > eps*k*k) {
x = 1/(x-a);
a = Math.floor(x);
h2 = h1; h1 = h;
k2 = k1; k1 = k;
h = h2 + a*h1;
k = k2 + a*k1;
}
return h + "/" + k;
}
, eps = 1.0E-15. , . ( while .)
( while):
getlowestfraction(0.5) = 1/2 (1 iteration)
getlowestfraction(0.125) = 1/8 (1 iteration)
getlowestfraction(0.1+0.2) = 3/10 (2 iterations)
getlowestfraction(1.0/3.0) = 1/3 (1 iteration)
getlowestfraction(Math.PI) = 80143857/25510582 (12 iterations)
, 1/3 x = 1.0/3.0. x 10 - 3333333333/10000000000.
:
eps = 1.0E-15 getlowestfraction(0.142857) = 142857/1000000.eps = 1.0E-6 getlowestfraction(0.142857) = 1/7.