Last active
December 30, 2022 18:25
-
-
Save berikv/903ba265e79c634cbeff to your computer and use it in GitHub Desktop.
Exponential Moving Average
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works with Swift 4.2 as well. Thank you