Show implementation of continuous moving average filter in recursive form
Assistant
User
Show C language implementation of continuous moving average filter in recursive form
Assistant
A continuous moving average filter can be implemented in recursive form, known as an Exponential Moving Average (EMA) for digital signal processing. The recursive formula allows the filter to compute the moving average efficiently without needing to accumulate all the previous data points.
The equation for the Exponential Moving Average (EMA) can be expressed as:
( y[n] ) is the filtered output at the current time step ( n ).
( x[n] ) is the input signal at the current time step ( n ).
( \alpha ) is the smoothing factor (0 < α ≤ 1). A higher α gives more weight to recent observations.
Implementation
Here is a sample implementation in Python, which demonstrates a recursive moving average filter.
python
class ExponentialMovingAverage:
def __init__(self, alpha=0.1):
self.alpha = alpha
self.previous_output = None # Initialize previous output
def filter(self, x):
if self.previous_output is None:
# Initialize the first output to the first input value.
self.previous_output = x
else:
# Apply the recursive formula for EMA.
self.previous_output = self.alpha * x + (1 - self.alpha) * self.previous_output
return self.previous_output
# Example usage
if __name__ == "__main__":
import numpy as np
import matplotlib.pyplot as plt
# Generate a sample signal (e.g., noisy sine wave)
t = np.linspace(0, 1, 500)
original_signal = np.sin(2 * np.pi * 10 * t)
noise = np.random.normal(0, 0.5, original_signal.shape)
noisy_signal = original_signal + noise
# Create the exponential moving average filter
ema_filter = ExponentialMovingAverage(alpha=0.1)
filtered_signal = []
for x in noisy_signal:
filtered_signal.append(ema_filter.filter(x))
# Plotting the results
plt.figure(figsize=(12, 6))
plt.plot(t, original_signal, label='Original Signal', color='blue')
plt.plot(t, noisy_signal, label='Noisy Signal', color='red', alpha=0.5)
plt.plot(t, filtered_signal, label='Filtered Signal (EMA)', color='green')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Exponential Moving Average Filter')
plt.grid()
plt.show()
Explanation of the Code:
Class Definition: ExponentialMovingAverage initializes with a smoothing factor ( \alpha ) and a variable to hold the last output.
Filter Method: For each new input, it applies the EMA formula. If it's the first input, the previous output is initialized to the current input.
Example Usage:
A noisy sine wave signal is created.
The EMA filter is applied to smooth the noisy signal.
Results are visualized using matplotlib.
This recursive approach efficiently calculates the moving average, requiring only the last output and the current input to compute the new output, which is useful for real-time processing and low memory usage.
Certainly! Below is a C implementation of a continuous moving average filter using a recursive approach, specifically an Exponential Moving Average (EMA) filter. This implementation includes a function to initialize the filter and a function to apply the filter to incoming data.
C Code Implementation
c
#include <stdio.h>
typedef struct {
double alpha; // Smoothing factor
double previous_output; // Previous output value
int initialized; // Flag to check if the filter is initialized
} ExponentialMovingAverage;
// Function to initialize the EMA filter
void init_ema(ExponentialMovingAverage* ema, double alpha) {
ema->alpha = alpha;
ema->previous_output = 0.0; // Initialize the previous output
ema->initialized = 0; // Mark as uninitialized
}
// Function to apply the EMA filter
double apply_ema(ExponentialMovingAverage* ema, double x) {
if (!ema->initialized) {
// If not initialized, set first output to input value
ema->previous_output = x;
ema->initialized = 1;
} else {
// Apply the recursive EMA formula
ema->previous_output = ema->alpha * x + (1.0 - ema->alpha) * ema->previous_output;
}
return ema->previous_output;
}
int main() {
// Example usage
ExponentialMovingAverage ema;
double alpha = 0.1; // Example smoothing factor
init_ema(&ema, alpha);
// Sample input data (e.g., noisy signal)
double input_data[] = {1.0, 2.0, 1.5, 3.0, 2.5, 2.0, 1.0};
size_t data_size = sizeof(input_data) / sizeof(input_data[0]);
// Output the filtered results
printf("Filtered Output:\n");
for (size_t i = 0; i < data_size; ++i) {
double filtered_value = apply_ema(&ema, input_data[i]);
printf("Input: %f, Filtered: %f\n", input_data[i], filtered_value);
}
return 0;
}
Explanation of the Code:
Struct Definition:
The ExponentialMovingAverage struct holds the smoothing factor (alpha), the previous output, and an initialization flag.
Initialization Function:
The init_ema function initializes the EMA filter with the smoothing factor and resets the previous output. It also sets the initialized flag to indicate if the filter has been used.
Filtering Function:
The apply_ema function checks if the filter has been initialized. If not, the first output is set to the input value. If it has been initialized, it applies the EMA formula using the current input value and the previous output.
Main Function:
An example usage is provided with a set of sample input data. The program prints each input value alongside its corresponding filtered value.
Compiling and Running the Code:
To compile and run this code, you can use any standard C compiler. For example, if you're using GCC, you can compile and run the program with the following commands:
bash
gcc -o ema_filter ema_filter.c
./ema_filter
This will output the input values and their corresponding filtered values calculated through the EMA filter, illustrating how the filter reacts to the input data.