Skip to content

Instantly share code, notes, and snippets.

@joni
joni / float2rat.js
Last active November 29, 2018 15:11 — forked from anonymous/float2rat.js
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);