Skip to content
This repository was archived by the owner on Apr 23, 2025. It is now read-only.

Commit d7534fa

Browse files
dan-zhengsaeta
authored andcommitted
Minor changes to average/standard deviation calculation. (#266)
- Use `Array.reduce(into:)` for efficiency. - Add `Array.variance` helper property.
1 parent 564951c commit d7534fa

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

Benchmarks/PrintingStyle.swift

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -108,23 +108,24 @@ func printJSON<T: Encodable>(_ value: T) {
108108

109109
/// Statistics-related helpers.
110110
extension Array where Element == Double {
111-
/// Average value across all elements of the array.
111+
/// The average value of elements.
112112
var average: Element {
113-
guard self.count > 0 else { return 0.0 }
114-
guard self.count > 1 else { return self.first! }
113+
guard count > 0 else { return 0 }
114+
guard count > 1 else { return first! }
115+
return (reduce(into: 0) { $0 += $1 }) / Double(count)
116+
}
115117

116-
return (self.reduce(0.0) { $0 + $1 }) / Double(self.count)
118+
/// The variance of elements.
119+
var variance: Element {
120+
guard count > 0 else { return 0 }
121+
guard count > 1 else { return 0 }
122+
let deltaDegreesOfFreedom = 1
123+
let squaredDeviationsSum = reduce(into: 0) { $0 += ($1 - average) * ($1 - average) }
124+
return squaredDeviationsSum / Double(count - deltaDegreesOfFreedom)
117125
}
118126

119-
/// Standard deviation of elements within the array.
127+
/// The standard deviation of elements.
120128
var standardDeviation: Element {
121-
guard self.count > 0 else { return 0.0 }
122-
guard self.count > 1 else { return 0.0 }
123-
124-
let average = self.average
125-
126-
return Foundation.sqrt(
127-
self.reduce(0.0) { $0 + ($1 - average) * ($1 - average) }
128-
/ Double(self.count - 1))
129+
return Double.sqrt(variance)
129130
}
130131
}

0 commit comments

Comments
 (0)