# Implementation of Linear convolution, Circular Convolution, and Linear Using Circular Convolution in Python: Full Source Code in Python Implementation of Linear convolution, Circular Convolution, and Linear Using Circular Convolution in Python: Full Source Code in Python

What is Convolution?
1. It is a mathematical operation that is performed on two functions or equations and the results of this produce a third function.
2. It is the result of the two functions after one is reversed and shifted.

Code:

def circular_convolution(x, y):

product = []

g = x[::-1]

for i in range(0, len(x)):

g = g[-1:] + g[:-1]

product.append(sum([a*b for a, b in zip(g, y)]))

return product

def linear_using_circular(x, y):

m, n = len(x), len(y)

x   = x + *(len(x)-m+n-1)

y   = y + *(len(y)-m+n-1)

product = circular_convolution(x, y)

return product

def linear_convolution(x, y, ox, oy):

p = [[a*b for a in x] for b in y]

product = dict()

for i in range(len(p)):

for j in range(len(p)):

if (i+j) in product:

product[i+j] += p[i][j]

else:

product[i+j] = p[i][j]

return [k for k in product.items()]

if __name__ == '__main__':

x   = [0, 1, 2, 3]

y   = [2, 1, 1, 2] ox, oy = 0, 0

linear_conv = linear_convolution(x, y, ox, oy) circular_conv = circular_convolution(x, y)

linear_using_circular_conv = linear_using_circular(x, y) print("Signal X: ", x, " with origin at index ", ox) print("Signal Y: ", y, " with origin at index ", oy) print("Linear Convolution: ", linear_conv,

" with origin ", (ox+oy))

print("Circular Convolution: ", circular_conv)

print("Linear using Circular Convolution: ", linear_using_circular_conv)

Note: Insert indentations wherever required.