Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2013 23:15
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 anonymous/4569504 to your computer and use it in GitHub Desktop.
Save anonymous/4569504 to your computer and use it in GitHub Desktop.
JavaScript function to convert a floating point number into a ratio with the help of some continued fractions.
function float2rat(x) {
tolerance = 1.e-4;
h1=1; h2=0;
k1=0; k2=1;
b = x;
do {
a = Math.floor(b);
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