/
mode.go
42 lines (38 loc) · 897 Bytes
/
mode.go
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
package stat
import (
"sort"
"github.com/BluntSporks/calculation"
)
// Mode returns the most common value(s), if any.
// See https://en.wikipedia.org/wiki/Mode_%28statistics%29.
func Mode(vals []float64) []float64 {
// Sort the values so we can compare for near equality.
sort.Float64s(vals)
cnts := make(map[float64]int)
max := 0
prev := 0.0
for _, val := range vals {
if calc.Near(val, prev) {
// Discard trivial differences between floating point values.
val = prev
} else {
// Only save the change once a sufficient difference has occurred.
prev = val
}
cnts[val]++
if cnts[val] > max {
max = cnts[val]
}
}
modes := make([]float64, 0, len(cnts))
// A mode must occur more than once.
if max > 1 {
for val, cnt := range cnts {
if cnt == max {
// Every val with a max count is a mode.
modes = append(modes, val)
}
}
}
return modes
}