Created
October 22, 2018 10:29
-
-
Save infovore/9f764145b6887032d43dd4cc93a36082 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 float_to_fraction (x, error) { | |
if (error === undefined) { | |
error = 0.000001; | |
} | |
var n = parseInt(Math.floor(x)); | |
x = x-n; | |
if(x < error) { | |
return [n,1]; | |
} else if(1-error < x) { | |
return [n+1,1]; | |
} | |
// The lower fraction is 0/1 | |
var lower_n = 0 | |
var lower_d = 1 | |
// The upper fraction is 1/1 | |
var upper_n = 1 | |
var upper_d = 1 | |
while(true) { | |
// The middle fraction is (lower_n + upper_n) / (lower_d + upper_d) | |
var middle_n = lower_n + upper_n | |
var middle_d = lower_d + upper_d | |
// If x + error < middle | |
if(middle_d * (x + error) < middle_n) { | |
// middle is our new upper | |
upper_n = middle_n | |
upper_d = middle_d | |
} else if(middle_n < (x - error) * middle_d) { | |
// Else If middle < x - error | |
// middle is our new lower | |
lower_n = middle_n | |
lower_d = middle_d | |
} else { | |
// Else middle is our best fraction | |
return [n * middle_d + middle_n, middle_d]; | |
} | |
} | |
} | |
if(!process.argv[2] && !process.argv[3]) { | |
console.log("Usage: node fraction.js NOMINATOR DENOMINATOR"); | |
process.exit(); | |
} | |
var numerator = parseFloat(process.argv[2]) | |
var denominator = parseFloat(process.argv[3]) | |
console.log(float_to_fraction(numerator/denominator, 0.1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment