Created
October 21, 2015 19:23
-
-
Save yurydelendik/1a5b7250ec527d0ea214 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function approximateFraction(x) { | |
// shourtcuts | |
if (Math.floor(x) === x) { | |
return [x, 1]; | |
} | |
var xinv = 1 / x; | |
if (Math.floor(xinv) === xinv) { | |
return [1, xinv]; | |
} | |
var x_ = x > 1 ? xinv : x; | |
// a/b and c/d are neighbours in Farley sequence. | |
var a = 0, b = 1, c = 1, d = 1; | |
// Limiting search to order 8. | |
var limit = 8; | |
while (true) { | |
// Generating next term in sequence (order of q). | |
var p = a + c, q = b + d; | |
if (q > limit) { | |
break; | |
} | |
if (x_ <= p / q) { | |
c = p; d = q; | |
} else { | |
a = p; b = q; | |
} | |
} | |
// select closest of the neighbours to x | |
if (x_ - a / b < c / d - x_) { | |
return x_ === x ? [a, b] : [b, a]; | |
} else { | |
return x_ === x ? [c, d] : [d, c]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment