-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontinued_fractions_convergents.sf
46 lines (38 loc) · 1.2 KB
/
continued_fractions_convergents.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
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 14 July 2017
# https://github.com/trizen
# A simple algorithm to get the continued fraction convergents for a given real value.
func num2cfrac(n, r=10) {
gather {
r.times {
var m = n.floor.int
take(m)
n = 1/((n - m) || break)
}
}
}
func cfrac2num(f) {
f.reverse.reduce {|a,b| b + 1/a }
}
func convergents(n, r) {
r.of { |i|
cfrac2num(num2cfrac(n, i+1))
}
}
# Any real value
var v = Num.pi
# Get the convergent fractions and display them
convergents(v, 10).each { |n|
say (n, " -> ", n.as_frac)
}
__END__
3.14285714285714285714285714285714285714285714286 -> 22/7
3.14150943396226415094339622641509433962264150943 -> 333/106
3.14159292035398230088495575221238938053097345133 -> 355/113
3.14159265301190260407226149477372968400700863996 -> 103993/33102
3.14159265392142104470871594159265392142104470872 -> 104348/33215
3.14159265346743670552045478534915632492422757362 -> 208341/66317
3.14159265361893662339750030141060161556082465941 -> 312689/99532
3.14159265358107777120441930658185778183065102626 -> 833719/265381
3.14159265359140397848254241421927966391989323483 -> 1146408/364913