The propose is to calculate incrementally the average The code below is the best way I found to calculate incremental average, in order to use it for big numbers and or great array
The following is an example give this array doubles
let values = [14.0,12.0, 23.4,37.5,11.46]
var index = 1
let avg = values.reduce(0.0) { return $0 + ( $1 - $0 ) / Double(index++) }
avg will be 19.672. and it works.
Is it correct from your point of view?
Is there a way in order to accomplish this with something like:
let avg = values.averageIncr()
What I don't like is that I have to use and index?
[updated]
a step further, thanks to @Martin R contribute
protocol NumericType:Equatable {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
init(_ value : Int)
}
extension Double : NumericType { }
extension Array where Element : NumericType {
mutating func avg_inc_adding( element: Element, var startAvg:Element? = Element(0) ) throws -> Element{
if count > 0 && startAvg! == Element(0) {
startAvg = self.avg_inc()
}
append(element)
return startAvg! + (element - startAvg!) / Element(self.count - 1)
}
func avg_inc() -> Element {
return enumerate().reduce(Element(0)) { $0 + ( $1.1 - $0 ) / Element($1.0 + 1) }
}
}
in this way I'm be able to do something like:
var average:Double = values.avg_inc()
do {
average = try values.avg_inc_adding(34.6,startAvg: z)
}catch {
}
that fit with my needs, and I hope with the ones for somebody else.