fraction icon indicating copy to clipboard operation
fraction copied to clipboard

Checkin Javascript Version

Open clord opened this issue 14 years ago • 0 comments

I wrote a javascript version of the algorithm:

// Haven't quite tested this guy yet.
function fraction(flt) {
    var maxden = 4;
    var num, m12, den, m22;
    var x, tmp, ai;
    var whole = 0.0;
    if (flt < 0.0) {
            rs = fraction(-flt);
            rs.num *= -1;
            return rs;
    }
    if (flt > 1.0)
            flt -= whole = Math.floor(flt);

    num = m22 = 1; m12 = den = 0;
    x = flt;
    while ((den * (ai = Math.floor(x)) + m22) <= maxden) {
            tmp = m12; m12 = num;
            num = Math.floor(num * ai + tmp);
            tmp = m22; m22 = den;
            den = Math.floor(den * ai + tmp);
            if (x == ai) break;
            if (Math.abs(x - ai) < 0.000000000001) break;
            x = 1.0 / (x - ai);
    }
    return { Whole: whole, Num: num, Den: den, Err: flt - num/den};
}

clord avatar Feb 28 '11 15:02 clord