Skip to content

Instantly share code, notes, and snippets.

@mikesmullin
Last active July 15, 2018 16:00
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 mikesmullin/6043986 to your computer and use it in GitHub Desktop.
Save mikesmullin/6043986 to your computer and use it in GitHub Desktop.
Cumulative Moving Average (lets you calculate average in the middle of a stream of numbers)
avg = (a) ->
sum = 0
for v in a
sum += v
sum / a.length
cavg = (v, av, c) ->
av + ((v - av) / c)
console.log '---'
console.log avg [1,2,3,4]
console.log avg [1,2,3,4,5]
console.log cavg 5, 2.5, 5 # notice cavg() == avg() above
# see also:
# https://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment