L8EasyPart L · Classical ML & Statistical Simulation
Moving Average (Sliding Window & Exponential)
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?
💡
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
### Incremental Window Update & Prefix-Sum Queries
Naive window summation costs .
1. Sliding queue: Each step adds the entering value and subtracts the exiting value in : ;
2. Prefix sums: Precomputing answers arbitrary range sums in (watch float drift over long streams by periodically recomputing or using Kahan summation).
Naive window summation costs .
1. Sliding queue: Each step adds the entering value and subtracts the exiting value in : ;
2. Prefix sums: Precomputing answers arbitrary range sums in (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.