|
| 1 | +/* |
| 2 | +* Reference: https://en.wikipedia.org/wiki/Farey_sequence |
| 3 | +* Inspiration: https://www.youtube.com/watch?v=7LKy3lrkTRA |
| 4 | +* |
| 5 | +* Farey Approximation algorithm is an algorithm to |
| 6 | +* approximate a reduced fraction value for a certain |
| 7 | +* decimal number x where 0 < x < 1. |
| 8 | +* |
| 9 | +* The algorithm works by keeping two fractional upper and |
| 10 | +* lower bounds which start at 0 / 1 and 1 / 1. These values |
| 11 | +* are then used to find the "mediate" which is a value between |
| 12 | +* the two fractions. |
| 13 | +* |
| 14 | +* For any two fractions a / b and c / d, |
| 15 | +* mediate = a + c / b + d |
| 16 | +* |
| 17 | +* Then it is checked if the decimal is greater than or less |
| 18 | +* than the mediate and then the lower or the upper value is |
| 19 | +* set to be the mediate respectively. |
| 20 | +* |
| 21 | +* This is repeated for n times and then the mediate is |
| 22 | +* returned. |
| 23 | +* |
| 24 | +* This is explained in a greater detail in the "Inspiration" |
| 25 | +* link. |
| 26 | +*/ |
| 27 | + |
| 28 | +function fareyApproximation (decimal, repeat = 20) { |
| 29 | + let a = 0; let b = 1; let c = 1; let d = 1; let numerator; let denominator |
| 30 | + |
| 31 | + for (let i = 0; i < repeat; i++) { |
| 32 | + numerator = a + c |
| 33 | + denominator = b + d |
| 34 | + |
| 35 | + if (decimal > numerator / denominator) { |
| 36 | + [a, b] = [numerator, denominator] |
| 37 | + } else { |
| 38 | + [c, d] = [numerator, denominator] |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return { numerator, denominator } |
| 43 | +} |
| 44 | + |
| 45 | +export { fareyApproximation } |
0 commit comments