Skip to content

Instantly share code, notes, and snippets.

@berikv
Last active December 30, 2022 18:25
Show Gist options
  • Select an option

  • Save berikv/903ba265e79c634cbeff to your computer and use it in GitHub Desktop.

Select an option

Save berikv/903ba265e79c634cbeff to your computer and use it in GitHub Desktop.
Exponential Moving Average
func exponentialMovingAverage(currentAverage: Double, newValue: Double, smoothing: Double) -> Double {
return smoothing * newValue + (1 - smoothing) * currentAverage
}
// Usage:
// var a = 3
// a = exponentialMovingAverage(a, 8, 0.5)
// Swift 2
struct ExponentialMovingAverage {
var currentValue: Double
let smoothing: Double
init(initialValue: Double = 0, smoothing: Double = 0.5) {
self.currentValue = initialValue
self.smoothing = smoothing
}
mutating func update(next: Double) -> Double {
currentValue = smoothing * next + (1 - smoothing) * currentValue
return currentValue
}
}
extension ExponentialMovingAverage: CustomStringConvertible, CustomDebugStringConvertible {
var description: String { return "average = \(currentValue)" }
var debugDescription: String { return "<ExponentialMovingAverage smoothnig = \(smoothing), currentValue = \(currentValue)" }
}
extension ExponentialMovingAverage: Equatable {}
func ==(lhs: ExponentialMovingAverage, rhs: ExponentialMovingAverage) -> Bool {
return lhs.smoothing == rhs.smoothing && lhs.currentValue == rhs.currentValue
}
// Usage
var average = ExponentialMovingAverage(initialValue: 3)
average.update(5)
average.update(5)
average
@BroderickHigby
Copy link
Copy Markdown

Works with Swift 4.2 as well. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment