-
Notifications
You must be signed in to change notification settings - Fork 1
/
taylor.zlang
64 lines (62 loc) · 1.37 KB
/
taylor.zlang
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
import Decimal: "./Decimal"
def sequence: func (biop) func (start, term) {
start: Decimal(start)
return [
"approx": func (amt, ...prefs) {
amt: Decimal(amt)
let result: start
{} ++ loop (num <- start to amt) result: biop(result, term(num, ...prefs))
return result
}
]
}
def taylor: [
"sum": sequence(+),
"prod": sequence(*),
"seq": sequence
]
def fac: func (num) {
if num = 0 {
return 1
}
return Decimal(1) to num |> .reduce(*)
}
taylor.E: taylor.sum(0, func Decimal(1)./(fac(x!), digit!))
taylor.PI: taylor.sum(0, func (x, digit) {
x: Decimal(x)
if x = 0 {
return 4
}
let sign: 1
if not(x / 2 = Decimal.floor(x / 2)) {
sign: -1
}
return Decimal(4)./(x * 2 + 1, digit) * sign
})
taylor.sin: taylor.sum(0, func (k, x) {
x: Decimal(x)
if k = 0 {
return x
}
let sign: 1
if k % 2 = 1 {
sign: -1
}
def amt: k * 2 + 1
def expResult: Array(amt |> .toNumber()).fill(x).reduce(*)
return expResult / fac(amt) * sign
})
taylor.cos: taylor.sum(0, func (k, x) {
x: Decimal(x)
if k = 0 {
return 1
}
let sign: 1
if k % 2 = 1 {
sign: -1
}
def amt: k * 2
def expResult: Array(amt |> .toNumber()).fill(x).reduce(*)
return expResult / fac(amt) * sign
})
export taylor