Skip to content

Instantly share code, notes, and snippets.

@rolandkakonyi
Last active January 29, 2018 13:37
Show Gist options
  • Save rolandkakonyi/07b61a188ffb30b953779d7752a76fb4 to your computer and use it in GitHub Desktop.
Save rolandkakonyi/07b61a188ffb30b953779d7752a76fb4 to your computer and use it in GitHub Desktop.
//
// Created by Roland Kakonyi on 2018. 01. 29.
// Based on https://github.com/edekhayser/Tweeting-in-Swift
//
import Foundation
/**Arithmetic Mean
:param: array The array that the arithmetic mean will be found for.
:returns: The arithmetic mean of the input array.
*/
func aMean(_ array: [Double]) -> Double {
return array.reduce(0.0, +) / Double(array.count)
}
/**Geometric Mean
:param: array The array that the geometric mean will be found for.
:returns: The geometric mean of the input array.
*/
func gMean(_ array: [Double]) -> Double {
return pow(array.reduce(1.0, *), 1.0 / Double(array.count))
}
/**Median
:param: array The array that the median will be found for.
:returns: The median of the input array.
*/
func med(_ array: [Double]) -> Double {
var sorted = array.sorted(by: <)
let l = sorted.count
return l % 2 == 0 ? (sorted[l / 2] + sorted[l / 2 + 1]) / 2 : sorted[l / 2]
}
/**Standard Deviation (Population)
:param: array The array that the population standard deviation will be found for.
:returns: The population standard deviation of the input array.
*/
func stdDevPop(_ array: [Double]) -> Double {
let mean = aMean(array)
return pow(aMean(array.map {
pow(($0 - mean), 2)
}), 0.5)
}
/**Standard Deviation (Sample)
:param: array The array that the sample standard deviation will be found for.
:returns: The sample standard deviation of the input array.
*/
func stdDevSample(_ array: [Double]) -> Double {
let mean = aMean(array)
return pow(array.map {
pow(($0 - mean), 2)
}.reduce(0.0, +) / Double(array.count - 1), 0.5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment