forked from sheetjs/sheetjs
23 lines
585 B
JavaScript
23 lines
585 B
JavaScript
function frac(x, D, mixed) {
|
|
var sgn = x < 0 ? -1 : 1;
|
|
var B = x * sgn;
|
|
var P_2 = 0, P_1 = 1, P = 0;
|
|
var Q_2 = 1, Q_1 = 0, Q = 0;
|
|
var A = Math.floor(B);
|
|
while(Q_1 < D) {
|
|
A = Math.floor(B);
|
|
P = A * P_1 + P_2;
|
|
Q = A * Q_1 + Q_2;
|
|
if((B - A) < 0.0000000005) break;
|
|
B = 1 / (B - A);
|
|
P_2 = P_1; P_1 = P;
|
|
Q_2 = Q_1; Q_1 = Q;
|
|
}
|
|
if(Q > D) { Q = Q_1; P = P_1; }
|
|
if(Q > D) { Q = Q_2; P = P_2; }
|
|
if(!mixed) return [0, sgn * P, Q];
|
|
if(Q===0) throw "Unexpected state: "+P+" "+P_1+" "+P_2+" "+Q+" "+Q_1+" "+Q_2;
|
|
var q = Math.floor(sgn * P/Q);
|
|
return [q, sgn*P - q*Q, Q];
|
|
}
|