Skip to content

Commit bb85eca

Browse files
authored
chore: Merge pull request TheAlgorithms#638 from raklaptudirm/master
Add Farey Approximation Algorithm
2 parents 8ff4e4c + e5b7e56 commit bb85eca

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

Maths/FareyApproximation.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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 }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { fareyApproximation } from '../FareyApproximation'
2+
3+
describe('fareyApproximation', () => {
4+
it('Return Farey Approximation of 0.7538385', () => {
5+
const approx = fareyApproximation(0.7538385)
6+
expect(approx).toStrictEqual({ numerator: 52, denominator: 69 })
7+
})
8+
9+
it('Return Farey Approximation of 0.23584936', () => {
10+
const approx = fareyApproximation(0.23584936)
11+
expect(approx).toStrictEqual({ numerator: 196, denominator: 831 })
12+
})
13+
})

0 commit comments

Comments
 (0)