Skip to content

Instantly share code, notes, and snippets.

@jevgen
Forked from anonymous/float2rat.js
Created January 19, 2017 18:18
Show Gist options
  • Save jevgen/d3d3e96000c4e9bd77c6f277e1237fd8 to your computer and use it in GitHub Desktop.
Save jevgen/d3d3e96000c4e9bd77c6f277e1237fd8 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