Last active
November 15, 2017 16:16
-
-
Save dropmeaword/b2808b6a30fcd73d929a06562eaa5212 to your computer and use it in GitHub Desktop.
This bit of code, uses the update funtion to calculate a dynamic running average that can be used for accurate analog sensing.
This file contains 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
class MovingStats: | |
def __init__(self, alphaOrN): | |
self.mean = 0 | |
self.var = 0 | |
self.started = False | |
if (alphaOrN > 1): | |
self.alpha = 2 / (alphaOrN - 1) | |
else: | |
self.alpha = alphaOrN | |
def update(self, value): | |
if (not self.started): | |
self.mean = value | |
self.var = 0 | |
self.started = True | |
else: | |
self.mean = self.mean - self.alpha * (self.mean - value); | |
diff = value - self.mean | |
self.var = self.var - self.alpha * (self.var - diff*diff); | |
def normalize(self, value): | |
stddev = math.sqrt(self.var) | |
return ( value - self.mean ) / (stddev + 1e-10) | |
def normalize01(self, value): | |
norm = self.normalize(value) | |
norm = norm / 6.0 + 0.5 # I'm actually not sure why this magical number 6 is here, maybe it has to be tested because this was made for the specific purpose of sensing heartbeats | |
return norm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment