-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequence_succesive_differences.sf
54 lines (41 loc) · 1.06 KB
/
sequence_succesive_differences.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
#!/usr/bin/ruby
# Compute the successive differences of a given sequence.
# An Introduction to "sequences" and discrete calculus:
# https://www.youtube.com/watch?v=J-Gow6SfG2c
func differences(seq) {
var deltas = [seq]
seq.end.times {
seq = seq.map_cons(2, {|a,b| b - a })
deltas << seq
}
return deltas
}
say "=> Difference of powers:"
for n in (0 .. 5) {
say differences(n+1 -> of {|k| k**n })
}
say "\n=> First 10 factorials:"
# This is equivalent with the following formula:
# n! = Sum_{k=0..n} binomial(n, k) * (n-k)^n * (-1)^k
for n in (^10) {
say ("#{n}! = ", differences(n+1 -> of {|k| k**n })[-1][0])
}
__END__
=> Difference of powers:
[[1]]
[[0, 1], [1]]
[[0, 1, 4], [1, 3], [2]]
[[0, 1, 8, 27], [1, 7, 19], [6, 12], [6]]
[[0, 1, 16, 81, 256], [1, 15, 65, 175], [14, 50, 110], [36, 60], [24]]
[[0, 1, 32, 243, 1024, 3125], [1, 31, 211, 781, 2101], [30, 180, 570, 1320], [150, 390, 750], [240, 360], [120]]
=> First 10 factorials:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880