Created
January 31, 2015 04:08
-
-
Save mobyjames/986c1679e452cc77c1f3 to your computer and use it in GitHub Desktop.
Moving Average
This file contains 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
class MovingAverage { | |
var samples: Array<Double> | |
var sampleCount = 0 | |
var period = 5 | |
init(period: Int = 5) { | |
self.period = period | |
samples = Array<Double>() | |
} | |
var average: Double { | |
let sum: Double = samples.reduce(0, combine: +) | |
if period > samples.count { | |
return sum / Double(samples.count) | |
} else { | |
return sum / Double(period) | |
} | |
} | |
func addSample(value: Double) -> Double { | |
var pos = Int(fmodf(Float(sampleCount++), Float(period))) | |
if pos >= samples.count { | |
samples.append(value) | |
} else { | |
samples[pos] = value | |
} | |
return average | |
} | |
} |
class MovingAverage {
var samples: Array
var sampleCount = 0
var period = 5
init(period: Int = 5) {
self.period = period
samples = Array<Double>()
}
var average: Double {
let sum: Double = samples.reduce(0, +)
if period > samples.count {
return sum / Double(samples.count)
} else {
return sum / Double(period)
}
}
func addSample(value: Double) -> Double {
sampleCount = sampleCount + 1
let pos = Int(fmodf(Float(sampleCount + 1), Float(period)))
if pos >= samples.count {
samples.append(value)
} else {
samples[pos] = value
}
return average
}
}
dont you think it is incorrect
it should look like this this
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is perfect. Thanks! FYI
pos
is never mutated and therefore should be declared withlet
instead ofvar