Skip to content

Instantly share code, notes, and snippets.

@bwhiteley
Created February 27, 2019 06:41
Show Gist options
  • Save bwhiteley/98de4a371f75fd836b04090bd0f97f1a to your computer and use it in GitHub Desktop.
Save bwhiteley/98de4a371f75fd836b04090bd0f97f1a to your computer and use it in GitHub Desktop.
naive statistics playground for kid's homework.
import Foundation
func mean(_ values: [Float]) -> Float {
return sum(values) / Float(values.count)
}
func median(_ values: [Float]) -> Float {
var sorted = values.sorted()
guard values.count > 0 else { return 0 }
while sorted.count > 2 {
sorted.popLast()
sorted.removeFirst()
}
return mean(sorted)
}
func sum(_ values: [Float]) -> Float {
var a: Float = 0
for i in values {
a = a + i
}
return a
}
func mode(_ values: [Float]) -> Float {
var counts: [Float: Int] = [:]
for i in values {
counts[i, default: 0] += 1
}
guard values.count > 0 else { return 0 }
let pairs = Array(counts.enumerated()).map{$0.element}
print(pairs)
return pairs.sorted { lhs, rhs in
return lhs.value < rhs.value
}.last!.key
}
func popStdDev(_ values: [Float]) -> Float {
let m = mean(values)
var sumOfSquaredDiffs: Float = 0
for i in values {
let diff = i - m
sumOfSquaredDiffs += diff * diff
}
return sqrtf(sumOfSquaredDiffs / Float(values.count))
}
let births: [Float] = [1,2,2,2,2,2,2,2,2,3,3,3,4,4,4]
median(births)
mean(births)
mode(births)
popStdDev(births)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment