L8EasyPart L · Classical ML & Statistical Simulation

Moving Average (Sliding Window & Exponential)

⚡Flashcard Drill➔

Sliding-window Simple Moving Average optimized to O(1) per step via prefix sums.

⏱️ Time: O(N) 线性单遍
💾 Space: O(N)
🎯 Interactive Self-Practice Loop (Attempt Before Peeking)
Practice in 4 steps: recall mechanism, complete core lines, check edge cases, and log mastery locally.
Step 1 · Mechanism Recall & Stability Self-Check
Step 2 · Complete Key Implementation Lines
import numpy as np
def simple_moving_average_cumsum(x: np.ndarray, window_size: int) -> np.ndarray:
"""利用前缀和 O(N) 极速计算滑动窗口均值"""
if window_size <= 0 or window_size > len(x):
raise ValueError("无效的窗口大小")
# 计算前缀和 (补 0 方便切片)
cumsum =
# 窗口和 = cumsum[w:] - cumsum[:-w]
return
Step 3 · Verify Boundary Cases & Assertions
Step 4 · Follow-Up Drill & Review Outcome
Q1: How can time-series monitoring protect moving averages against brief outlier spikes?
Next: LLM-as-a-Judge Position Swap & Cohen's Kappa →
💡

Core Mental Anchor / Mnemonic

Build prefix sums once and divide range differences (S[t] - S[t-W]) by window W in O(1).

📐 Mathematical Derivation & Core Formula

SMAt=1W∑i=t−W+1txi=SMAt−1+xt−xt−WW\mathrm{SMA}_t = \frac{1}{W} \sum_{i=t-W+1}^t x_i = \mathrm{SMA}_{t-1} + \frac{x_t - x_{t-W}}{W}
### Incremental Window Update & Prefix-Sum O(1)O(1) Queries
Naive window summation costs O(N⋅W)O(N \cdot W).
1. Sliding queue: Each step adds the entering value xtx_t and subtracts the exiting value xt−Wx_{t-W} in O(1)O(1): Sumt=Sumt−1+xt−xt−W\mathrm{Sum}_t = \mathrm{Sum}_{t-1} + x_t - x_{t-W};
2. Prefix sums: Precomputing Sk=∑i=1kxiS_k = \sum_{i=1}^k x_i answers arbitrary range sums Sum(a,b)=Sb−Sa−1\mathrm{Sum}(a, b) = S_b - S_{a-1} in O(1)O(1) (watch float drift over long streams by periodically recomputing or using Kahan summation).

🔄 Tensor Dimensions & Shape Flow

x: (N,) -> cumsum prefix array (N+1,) -> shifted slice difference / W -> sma: (N - W + 1,)

🛡️ Numerical Stability & Pitfalls Checklist

  • Prefix sums avoid incremental add/subtract floating-point drift on long series.
  • Pair with rolling median or trimmed mean when outlier spikes can corrupt baseline signals.

💻 Reference Code Implementation

import numpy as np

def simple_moving_average_cumsum(x: np.ndarray, window_size: int) -> np.ndarray:
    """利用前缀和 O(N) 极速计算滑动窗口均值"""
    if window_size <= 0 or window_size > len(x):
        raise ValueError("无效的窗口大小")
        
    # 计算前缀和 (补 0 方便切片)
    cumsum = np.cumsum(np.insert(x, 0, 0))
    # 窗口和 = cumsum[w:] - cumsum[:-w]
    return (cumsum[window_size:] - cumsum[:-window_size]) / float(window_size)

🧪 Runnable Assertions & Validation

Copy and run directly in Python / Jupyter:

import numpy as np
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
sma = simple_moving_average_cumsum(x, window_size=3)
# [1,2,3]->2.0; [2,3,4]->3.0; [3,4,5]->4.0
assert np.allclose(sma, [2.0, 3.0, 4.0])
print("✓ 滑动平均前缀和算法自测通过")

🎯 Core Follow-up Inquiries & Reference Answers

Q1:How can time-series monitoring protect moving averages against brief outlier spikes?
Replace simple means with a sliding median filter or trimmed moving average (dropping extreme top/bottom percentiles per window) so single-point glitches do not distort baseline trends.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔
← Prev: Reservoir Sampling AlgorithmBack to Part L & All 105Next: LLM-as-a-Judge Position Swap & Cohen's Kappa →