Skip to content

Instantly share code, notes, and snippets.

@samliu
Created May 25, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samliu/4476b0b7ebd281b78f422ca9e4e685da to your computer and use it in GitHub Desktop.
Save samliu/4476b0b7ebd281b78f422ca9e4e685da to your computer and use it in GitHub Desktop.
Playing with means
"""Playing with means.
Geometric and Arithmetric means will only ever be equal when every item on the
list is the same. So if you keep entering 2,2,2,2,2,2,etc the two averages will
be the same. As soon as a new value is in the list the two values will diverge.
You can use this to look at how much the values diverge by with the introduction of outliers.
"""
class MovingAvg(object):
def __init__(self):
self.numbers = []
self.n = 0
self.sum = 0
self.mult = 1
def AddInt(self, i):
if i < 0:
print("Can't insert negative value: {0}".format(i))
return False # Failed
self.numbers.append(i)
self.n += 1
self.sum += i
if i > 0:
self.mult *= i
return True # Success
def GetArithmeticMean(self):
if self.n == 0:
return 0
return self.sum/float(self.n)
def GetGeometricMean(self):
if self.n == 0:
return 0
return self.mult**(1/float(self.n))
if __name__ == "__main__":
calc = MovingAvg()
while True:
text = raw_input("Enter a number:")
calc.AddInt(int(text))
print("Numbers: {}".format(calc.numbers))
print("Arithmetic Mean: {}".format(calc.GetArithmeticMean()))
print("Geometric Mean: {}".format(calc.GetGeometricMean()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment