Skip to content

Instantly share code, notes, and snippets.

@philipperemy
Created January 13, 2021 23:06
Show Gist options
  • Select an option

  • Save philipperemy/0011d612031299787b17b2a58066579c to your computer and use it in GitHub Desktop.

Select an option

Save philipperemy/0011d612031299787b17b2a58066579c to your computer and use it in GitHub Desktop.

Revisions

  1. philipperemy created this gist Jan 13, 2021.
    28 changes: 28 additions & 0 deletions online_mean_std.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    import numpy as np

    # online computation of the mean and the variance.

    class RollingMean:

    def __init__(self):
    self.st = 0.0
    self.n = 0

    def update(self, x):
    self.st += x
    self.n += 1
    return self.st / self.n


    class RollingStd:

    def __init__(self):
    self.sst = 0.0
    self.st = 0.0
    self.n = 0

    def update(self, x):
    self.sst += x ** 2
    self.st += x
    self.n += 1
    return np.sqrt((self.sst - (self.st ** 2) / self.n) / self.n)