The moving median is a robust alternative to the moving average for smoothing time series. While the moving average is sensitive to outliers (a single spike can shift the average significantly), the median is unaffected by extreme values. This makes it ideal for signal processing, sensor data cleaning, and financial data where occasional spikes or errors occur.
Given a list of values and a window size, compute the median for each sliding window position.
For each window, sort the values. If the window size is odd, the median is the middle element. If even, it is the average of the two middle elements. The output has length n - window_size + 1.
Input:
values = [1, 3, 5, 7, 9], window_size = 3
Output:
[3.0, 5.0, 7.0]
Window [1,3,5] sorted -> median=3. Window [3,5,7] -> median=5. Window [5,7,9] -> median=7.
Input:
values = [1, 2, 3, 4], window_size = 2
Output:
[1.5, 2.5, 3.5]
Even window size: median of [1,2] = (1+2)/2 = 1.5, median of [2,3] = 2.5, median of [3,4] = 3.5.
For each window starting at position i, extract the slice values[i:i+window_size], sort it, and find the median. Remember that sorted() returns a new list without modifying the original.
For the median: if n is odd, return sorted_window[n//2]. If n is even, return (sorted_window[n//2-1] + sorted_window[n//2]) / 2.
Sign in to take notes on this problem
Accepts: array
Accepts: number
The moving median is a robust alternative to the moving average for smoothing time series. While the moving average is sensitive to outliers (a single spike can shift the average significantly), the median is unaffected by extreme values. This makes it ideal for signal processing, sensor data cleaning, and financial data where occasional spikes or errors occur.
Given a list of values and a window size, compute the median for each sliding window position.
For each window, sort the values. If the window size is odd, the median is the middle element. If even, it is the average of the two middle elements. The output has length n - window_size + 1.
Input:
values = [1, 3, 5, 7, 9], window_size = 3
Output:
[3.0, 5.0, 7.0]
Window [1,3,5] sorted -> median=3. Window [3,5,7] -> median=5. Window [5,7,9] -> median=7.
Input:
values = [1, 2, 3, 4], window_size = 2
Output:
[1.5, 2.5, 3.5]
Even window size: median of [1,2] = (1+2)/2 = 1.5, median of [2,3] = 2.5, median of [3,4] = 3.5.
For each window starting at position i, extract the slice values[i:i+window_size], sort it, and find the median. Remember that sorted() returns a new list without modifying the original.
For the median: if n is odd, return sorted_window[n//2]. If n is even, return (sorted_window[n//2-1] + sorted_window[n//2]) / 2.
Sign in to take notes on this problem
Accepts: array
Accepts: number