Created
October 9, 2012 15:41
-
-
Save herczy/3859615 to your computer and use it in GitHub Desktop.
Online average counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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