File tree Expand file tree Collapse file tree 1 file changed +11
-14
lines changed
src/main/java/com/thealgorithms/maths Expand file tree Collapse file tree 1 file changed +11
-14
lines changed Original file line number Diff line number Diff line change @@ -23,24 +23,21 @@ public static double[] convolution(double[] a, double[] b) {
23
23
double [] convolved = new double [a .length + b .length - 1 ];
24
24
25
25
/*
26
- The discrete convolution of two signals A and B is defined as:
27
-
28
- A.length
29
- C[i] = Σ (A[k]*B[i-k])
30
- k=0
31
-
32
- It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <=
33
- B.length - 1 From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get
34
- the conditions below.
26
+ * Discrete convolution formula:
27
+ * C[i] = Σ A[k] * B[i - k]
28
+ * where k ranges over valid indices so that both A[k] and B[i-k] are in bounds.
35
29
*/
30
+
36
31
for (int i = 0 ; i < convolved .length ; i ++) {
37
- convolved [i ] = 0 ;
38
- int k = Math .max (i - b .length + 1 , 0 );
32
+ double sum = 0 ;
33
+ int kStart = Math .max (0 , i - b .length + 1 );
34
+ int kEnd = Math .min (i , a .length - 1 );
39
35
40
- while (k < i + 1 && k < a .length ) {
41
- convolved [i ] += a [k ] * b [i - k ];
42
- k ++;
36
+ for (int k = kStart ; k <= kEnd ; k ++) {
37
+ sum += a [k ] * b [i - k ];
43
38
}
39
+
40
+ convolved [i ] = sum ;
44
41
}
45
42
46
43
return convolved ;
You can’t perform that action at this time.
0 commit comments