Skip to content

Data Science

Moving Average

This takes O(n) time overall if you reuse a running sum, dropping the oldest value and adding the new one, instead of re-summing the whole window each time. It takes O(n * k) time if you recompute the sum from scratch for each window of size k.

The idea, in plain English

A moving average smooths out noisy data by averaging a small sliding window of nearby values. This is like judging a runner's pace using their last 3 laps instead of just the latest one, so one unusually fast or slow lap does not throw off the whole picture. As the window slides forward one step at a time, you get a fresh average at each position.

How it works

  1. 1Pick a window size — how many consecutive values to average at once (for example, 3).
  2. 2Take the first window-size values and average them. That is the first moving average.
  3. 3Slide the window forward by one position and average again. Repeat until the window reaches the end of the data.

When you'd use it

Use this to smooth out short-term noise in a sequence of numbers over time, such as daily stock prices, sensor readings, or website traffic. This lets you see the underlying trend instead of every small bump.

Common beginner mistakes

  • Do not recompute the full sum for every window from scratch on large data. That is wasteful when you could just subtract the value leaving the window and add the value entering it.
  • Do not pick a window so large it smooths away the real signal along with the noise, or so small it barely smooths anything.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Data: 10 20 30 40 50 60
Window size: 3
Moving averages: 20.00 30.00 40.00 50.00

Not sure this is the right topic? See the learning paths → or where this leads →