-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneralized_continued_fraction.sf
65 lines (46 loc) · 1.41 KB
/
generalized_continued_fraction.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
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 18 January 2018
# https://github.com/trizen
# Numerical evaluation of a generalized continued fraction.
# See also:
# https://en.wikipedia.org/wiki/Generalized_continued_fraction
#
## Compute the continued fraction numerically
#
func contfrac2num (from, to, num, den) {
return 0 if (from > to)
num.run(from) / (den.run(from) + __FUNC__(from + 1, to, num, den))
}
#
## Compute only the numerator of the continued fraction
#
func cfrac_num(from, to, num, den) is cached {
return 1 if (to == from-1)
return 0 if (to == from)
den.run(to-1)*__FUNC__(from, to-1, num, den) + num.run(to-1)*__FUNC__(from, to-2, num, den)
}
#
## Compute only the denominator of the continued fraction
#
func cfrac_den(from, to, num, den) is cached {
return 1 if (to == from)
return 0 if (to == from-1)
den.run(to-1)*__FUNC__(from, to-1, num, den) + num.run(to-1)*__FUNC__(from, to-2, num, den)
}
var from = float(1)
var to = float(100)
#
## Example for [n=1..Infinity, n^2 / (2n+1)] = 4/Pi - 1
#
var num = {|n| n**2 }
var den = {|n| 2*n + 1 }
say contfrac2num(from, to, num, den)
say contfrac2num(from, to+100, num, den)
say contfrac2num(from, to+1000, num, den)
say contfrac2num(from, to+2000, num, den)
var a = cfrac_num(from, 30, num, den)
var b = cfrac_den(from, 30, num, den)
say "Numerator = #{a}"
say "Denominator = #{b}"
say "Expansion = #{a/b}"