Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Moving Average
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
}
}
@cmmartin

This comment has been minimized.

Copy link

cmmartin commented Mar 24, 2016

This is perfect. Thanks! FYI pos is never mutated and therefore should be declared with let instead of var

@jimijon

This comment has been minimized.

Copy link

jimijon commented Sep 13, 2017

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
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.