Skip to content

Instantly share code, notes, and snippets.

@mobyjames
Created January 31, 2015 04:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mobyjames/986c1679e452cc77c1f3 to your computer and use it in GitHub Desktop.
Save mobyjames/986c1679e452cc77c1f3 to your computer and use it in GitHub Desktop.
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
Copy link

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

@jimijon
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
}

}

@sultan-arshi
Copy link

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