The float in a car's fuel tank bounces as the fuel sloshes, so the raw level readings jump up and down even though the real level changes slowly. The dashboard shows a moving average instead: each reading is replaced by the mean of itself and its neighbours.
The window has an odd width w, so it reaches h = w // 2 samples to each side. The smoothed value at position k is the mean of x[k - h], ..., x[k + h]. Edge rule: near the start and the end some of those positions do not exist; leave them out and take the mean of only the samples that do exist (so the window shrinks at the edges). The output always has the same length as the input.
Write smooth(x, w) that returns the list of smoothed values. Press Run with plot(x) and plot(smooth(x, 5)) to see the bounce flattened.
Examples
Input: x = [40, 46, 37, 43, 40, 52, 34], w = 3
Output: [43.0, 41.0, 42.0, 40.0, 45.0, 42.0, 43.0]
Explanation: position 0 has no left neighbour, so it is (40 + 46) / 2 = 43.
Position 1 is (40 + 46 + 37) / 3 = 41; the last position is (52 + 34) / 2 = 43.
Input: x = [1, 2, 3], w = 5
Output: [2.0, 2.0, 2.0]
Explanation: the window is wider than the list, so every position averages all three readings.
Constraints
wis odd;w = 1leaves the signal unchanged- answers are compared with a tolerance of
1e-6
Goals
- Replace each sample by the mean of a window of its neighbours
- Follow a stated rule at the edges, where the window does not fit
- See how a wider window removes more noise and also more detail