Skip to content

Instantly share code, notes, and snippets.

@joni
Forked from anonymous/float2rat.js
Last active November 29, 2018 15:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joni/4569508 to your computer and use it in GitHub Desktop.
Save joni/4569508 to your computer and use it in GitHub Desktop.
A JavaScript function to find short rational number representations of floating point numbers, with the help of some continued fractions.
function float2rat(x) {
var tolerance = 1.0E-6;
var h1=1; var h2=0;
var k1=0; var k2=1;
var b = x;
do {
var a = Math.floor(b);
var aux = h1; h1 = a*h1+h2; h2 = aux;
aux = k1; k1 = a*k1+k2; k2 = aux;
b = 1/(b-a);
} while (Math.abs(x-h1/k1) > x*tolerance);
return h1+"/"+k1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment