Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active August 24, 2016 21:37
Show Gist options
  • Save TimSC/38e3c6c51c878424951b638034a0fcb9 to your computer and use it in GitHub Desktop.
Save TimSC/38e3c6c51c878424951b638034a0fcb9 to your computer and use it in GitHub Desktop.
Running weighted average
#By Tim Sheerman-Chase, 2016
#CC0 license
class RunningWeightedAverage(object):
def __init__(self):
self.val = 0.0
self.weightTotal = 0.0
def update(self, valIn, weight = 1.0):
scaling = weight / float(self.weightTotal + weight)
self.val = valIn * scaling + self.val * (1.0 - scaling)
self.weightTotal += weight
return self.val
def get(self):
return self.val
def extend(self, vals, weights):
for v, w in zip(vals, weights):
self.update(v, w)
return self.val
if __name__ == "__main__":
rwa = RunningWeightedAverage()
print rwa.extend([5, 6, 2], [0.25, 0.25, 0.5])
print "correct answer", 3.75
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment