Lesson 11 of 15
Moving Average Filter
Moving Average Filter
The moving average is the simplest digital filter. It smooths a signal by replacing each sample with the average of itself and the preceding samples:
This is a causal filter — it only uses past and current samples.
Zero-Padding at the Start
For , not enough past samples exist. We treat missing samples as zero:
This means the output array has the same length as the input.
Example:
Signal:
Frequency Response
The moving average is a low-pass filter — it attenuates high-frequency components. A longer window ( larger) gives stronger smoothing but slower response.
Your Task
Implement moving_average(x, M) with causal zero-padding. Return a list of the same length as .
def moving_average(x, M):
result = []
for n in range(len(x)):
window = x[max(0, n - M + 1):n + 1]
padded_sum = sum(window) # missing samples are 0
result.append(padded_sum / M)
return result
print([round(v, 4) for v in moving_average([1, 2, 3, 4, 5], 3)])
# [0.3333, 1.0, 2.0, 3.0, 4.0]Python runtime loading...
Loading...
Click "Run" to execute your code.