Skip to content

Commit 6b21312

Browse files
Update EMAFilter.java
refactor: simplify EMAFilter implementation - Reduce verbose comments to essential formula - Shorten variable names (emaValue -> ema, audioSignal -> signal) - Condense constructor validation and initialization - Maintain identical functionality and behavior
1 parent f325279 commit 6b21312

File tree

1 file changed

+16
-36
lines changed

1 file changed

+16
-36
lines changed
Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,28 @@
11
package com.thealgorithms.audiofilters;
22

33
/**
4-
* Exponential Moving Average (EMA) Filter for smoothing audio signals.
5-
*
6-
* <p>This filter applies an exponential moving average to a sequence of audio
7-
* signal values, making it useful for smoothing out rapid fluctuations.
8-
* The smoothing factor (alpha) controls the degree of smoothing.
9-
*
10-
* <p>Based on the definition from
11-
* <a href="https://en.wikipedia.org/wiki/Moving_average">Wikipedia link</a>.
4+
* EMA Filter for audio signal smoothing.
5+
* Formula: EMA[i] = alpha * signal[i] + (1-alpha) * EMA[i-1]
126
*/
137
public class EMAFilter {
148
private final double alpha;
15-
private double emaValue;
16-
/**
17-
* Constructs an EMA filter with a given smoothing factor.
18-
*
19-
* @param alpha Smoothing factor (0 < alpha <= 1)
20-
* @throws IllegalArgumentException if alpha is not in (0, 1]
21-
*/
9+
private double ema;
10+
2211
public EMAFilter(double alpha) {
23-
if (alpha <= 0 || alpha > 1) {
24-
throw new IllegalArgumentException("Alpha must be between 0 and 1.");
25-
}
12+
if (alpha <= 0 || alpha > 1) throw new IllegalArgumentException("Alpha must be in (0,1]");
2613
this.alpha = alpha;
27-
this.emaValue = 0.0;
2814
}
29-
/**
30-
* Applies the EMA filter to an audio signal array.
31-
*
32-
* @param audioSignal Array of audio samples to process
33-
* @return Array of processed (smoothed) samples
34-
*/
35-
public double[] apply(double[] audioSignal) {
36-
if (audioSignal.length == 0) {
37-
return new double[0];
38-
}
39-
double[] emaSignal = new double[audioSignal.length];
40-
emaValue = audioSignal[0];
41-
emaSignal[0] = emaValue;
42-
for (int i = 1; i < audioSignal.length; i++) {
43-
emaValue = alpha * audioSignal[i] + (1 - alpha) * emaValue;
44-
emaSignal[i] = emaValue;
15+
16+
public double[] apply(double[] signal) {
17+
if (signal.length == 0) return new double[0];
18+
19+
double[] result = new double[signal.length];
20+
ema = result[0] = signal[0];
21+
22+
for (int i = 1; i < signal.length; i++) {
23+
ema = alpha * signal[i] + (1 - alpha) * ema;
24+
result[i] = ema;
4525
}
46-
return emaSignal;
26+
return result;
4727
}
4828
}

0 commit comments

Comments
 (0)