-
Notifications
You must be signed in to change notification settings - Fork 62
/
Sigma.swift
98 lines (63 loc) · 1.88 KB
/
Sigma.swift
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import Foundation
/**
Collection of functions for statistical calculation.
Project home: https://github.com/evgenyneu/SigmaSwiftStatistics
*/
public struct Sigma {
/**
Calculates the maximum value in the array.
- parameter values: Array of decimal numbers.
- returns: The maximum value in the array. Returns nil for an empty array.
Example:
Sigma.max([3, 10, 6]) // 10
*/
public static func max(_ values: [Double]) -> Double? {
if let maxValue = values.max() {
return maxValue
}
return nil
}
/**
Calculates the mimimum value in the array.
- parameter values: Array of decimal numbers.
- returns: The mimimum value in the array. Returns nil for an empty array.
Example:
Sigma.min([5, 3, 10]) // -> 3
*/
public static func min(_ values: [Double]) -> Double? {
if let minValue = values.min() {
return minValue
}
return nil
}
/**
Computes the sum of array values.
- parameter values: Array of decimal numbers.
- returns: The sum of array values.
Example:
Sigma.sum([1, 3, 10]) // 14
*/
public static func sum(_ values: [Double]) -> Double {
return values.reduce(0, +)
}
/**
Computes arithmetic mean of values in the array.
http://en.wikipedia.org/wiki/Arithmetic_mean
- parameter values: Array of decimal numbers.
- returns: Arithmetic mean of values in the array. Returns nil for an empty array.
Formula:
A = Σ(x) / n
Where n is the number of values.
Example:
Sigma.average([1, 12, 19.5, -5, 3, 8]) // 6.416666666666667
*/
public static func average(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
return sum(values) / count
}
// MARK: - Protected functionality
static func sort(_ values: [Double]) -> [Double] {
return values.sorted { $0 < $1 }
}
}