Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Created June 14, 2021 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinmeiners/7118f8a962bbc8a4e1bc7d25c7cf6070 to your computer and use it in GitHub Desktop.
Save justinmeiners/7118f8a962bbc8a4e1bc7d25c7cf6070 to your computer and use it in GitHub Desktop.
static func mean<S: Sequence, T>(
of sequence: S,
oneScalar: T,
scale: (T, S.Element) -> S.Element
) -> S.Element? where S.Element: AdditiveArithmetic, T: FloatingPoint {
var it = sequence.makeIterator()
guard let initial = it.next() else {
return nil
}
var count = oneScalar
var mean = initial
while let x = it.next() {
mean = mean + scale(T(1) / count, x - mean)
count += oneScalar
}
return mean
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment