-
-
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.
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) { | |
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