Repository navigation
Expand file tree
/
Copy pathdiff.go
More file actions
48 lines (36 loc) · 1.42 KB
/
Copy pathdiff.go
File metadata and controls
48 lines (36 loc) · 1.42 KB
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
package stats
// Diff calculates the successive differences of the input slice,
// returning input[i] - input[i-1] for each i in 1..len(input)-1.
// The output has length len(input) - 1; a single-element input
// returns an empty slice.
func Diff(input Float64Data) ([]float64, error) {
if input.Len() == 0 {
return nil, ErrEmptyInput
}
diff := make([]float64, input.Len()-1)
for i := 1; i < input.Len(); i++ {
diff[i-1] = input[i] - input[i-1]
}
return diff, nil
}
// PercentChange calculates the fractional change between successive
// elements of the input slice, returning
// (input[i] - input[i-1]) / input[i-1] for each i in 1..len(input)-1.
// The output has length len(input) - 1; a single-element input
// returns an empty slice. A zero denominator follows IEEE 754
// semantics, yielding +Inf, -Inf, or NaN (for 0/0), matching the
// behavior of pandas pct_change.
func PercentChange(input Float64Data) ([]float64, error) {
if input.Len() == 0 {
return nil, ErrEmptyInput
}
change := make([]float64, input.Len()-1)
for i := 1; i < input.Len(); i++ {
change[i-1] = (input[i] - input[i-1]) / input[i-1]
}
return change, nil
}
// Diff returns the successive differences of the data
func (f Float64Data) Diff() ([]float64, error) { return Diff(f) }
// PercentChange returns the fractional change between successive elements of the data
func (f Float64Data) PercentChange() ([]float64, error) { return PercentChange(f) }