-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfarey_fraction_approximations_2.sf
73 lines (60 loc) · 2.56 KB
/
farey_fraction_approximations_2.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 22 April 2019
# https://github.com/trizen
# Rational approximation of a real number, using Farey fractions.
# See also:
# https://en.wikipedia.org/wiki/Farey_sequence
# https://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree
func farey_approximations(r, callback, n=10) {
var a1 = r.int
var b1 = 1
var a2 = a1+1
var b2 = 1
n.times {
var a3 = a1+a2
var b3 = b1+b2
if (a3 < r*b3) {
(a1, b1) = (a3, b3)
}
else {
(a2, b2) = (a3, b3)
}
callback(a3, b3)
}
}
var r = Num.e # any real value
farey_approximations(r, {|n,d|
printf("%-49s ≈ %s/%s\n", n/d, n, d)
}, 30)
__END__
2.5 ≈ 5/2
2.66666666666666666666666666666666666666666666667 ≈ 8/3
2.75 ≈ 11/4
2.71428571428571428571428571428571428571428571429 ≈ 19/7
2.72727272727272727272727272727272727272727272727 ≈ 30/11
2.72222222222222222222222222222222222222222222222 ≈ 49/18
2.72 ≈ 68/25
2.71875 ≈ 87/32
2.71794871794871794871794871794871794871794871795 ≈ 106/39
2.71830985915492957746478873239436619718309859155 ≈ 193/71
2.71818181818181818181818181818181818181818181818 ≈ 299/110
2.71823204419889502762430939226519337016574585635 ≈ 492/181
2.71825396825396825396825396825396825396825396825 ≈ 685/252
2.71826625386996904024767801857585139318885448916 ≈ 878/323
2.71827411167512690355329949238578680203045685279 ≈ 1071/394
2.71827956989247311827956989247311827956989247312 ≈ 1264/465
2.71828358208955223880597014925373134328358208955 ≈ 1457/536
2.71828171828171828171828171828171828171828171828 ≈ 2721/1001
2.71828236824983734547820429407937540663630448926 ≈ 4178/1537
2.71828211189913317572892040977147360126083530339 ≈ 6899/2538
2.7182820005651313930488838654987284543656400113 ≈ 9620/3539
2.71828193832599118942731277533039647577092511013 ≈ 12341/4540
2.71828189857426457318173614870961920231005233712 ≈ 15062/5541
2.71828187098746560684805869764597982268419443595 ≈ 17783/6542
2.71828185072252419461752618321622696539838260639 ≈ 20504/7543
2.71828183520599250936329588014981273408239700375 ≈ 23225/8544
2.71828182294394971189104243059193294918805657412 ≈ 25946/9545
2.71828182873569572668472552379899386367405605617 ≈ 49171/18089
2.71828182673518129840052109719910255482376782225 ≈ 75117/27634
2.71828182752662773658771296721562452157557465608 ≈ 124288/45723