Skip to content

Instantly share code, notes, and snippets.

@herczy
Created October 9, 2012 15:41
Show Gist options
  • Select an option

  • Save herczy/3859615 to your computer and use it in GitHub Desktop.

Select an option

Save herczy/3859615 to your computer and use it in GitHub Desktop.
Online average counter
import math
class Calculator(object):
def __init__(self):
self.__count = 0
self.__sum = 0.0
self.__sqsum = 0.0
@property
def average(self):
return self.__sum / float(self.__count)
@property
def distribution(self):
return math.sqrt(self.__count * self.__sqsum - self.__sum ** 2) / self.__count
def add_number(self, num):
self.__count += 1
self.__sum += num
self.__sqsum += num ** 2
def add_iter(self, iter):
for num in iter:
self.add_number(num)
if __name__ == '__main__':
c = Calculator()
for i in range(-2, 3):
c.add_number(i)
print i, c.average, c.distribution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment