Last active
November 21, 2024 09:54
-
-
Save mindon/9cd2a690a1055470ddd1e43d1182a5a1 to your computer and use it in GitHub Desktop.
try to get a fraction of a number
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
// fraction gets up/down from a number | |
export function fraction(v: number, { precise = 5, tries = 100 }): string { | |
const [ul, dl] = [[0, 1], [1, 0]]; | |
const max = parseInt((v - Math.floor(v)).toString().substring(2)); | |
let [previous, current] = [NaN]; | |
let c = v; | |
for (let i = 2; i < tries; i++) { | |
const n = Math.floor(c); | |
const uc = n * ul[i - 1] + ul[i - 2]; | |
if (Math.abs(ul[i]) > max) { | |
break; | |
} | |
const dc = n * dl[i - 1] + dl[i - 2]; | |
if (precise && dc.toString().length > precise) { | |
break; | |
} | |
ul[i] = uc; | |
dl[i] = dc; | |
current = uc / dc; | |
if (current === previous || current === v) { | |
break; | |
} | |
previous = current; | |
c = 1 / (c - n); | |
} | |
const i = ul.length - 1; | |
if (i < 2) { | |
return { u: v, d: 1 }; | |
} | |
return { u: ul[i], d: dl[i] }; | |
} | |
// const v = 0.35141581; // 5 * Math.PI / 11; | |
// const precise = 8; | |
// console.log( | |
// fraction(v / Math.PI, { precise }), | |
// v.toPrecision(precise), | |
// (Math.PI * 6525397 / 58335848).toPrecision(precise), | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment