-
-
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.
This file contains 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 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