简体   繁体   中英

How to represent a square wave in python and how to convolve it?

I am trying to convolve a square wave with itself more than once and see the resulting graph. I know how to do convolution by my hands but I am not experienced in signal processing with Python. So my questions are:

  1. How can I represent a signal in Python? For example:

x(t) = 1 , 0 ≤ t ≤ 1

x(t) = 0, otherwise

  1. How can I convolve this square wave with itself?

What I have come so far is that I must use numpy's built-in convolve method; but the problem is I am stuck representing this square wave.

One way to create a suitable 0-1 array is np.fromfunction , passing it a function that returns True within the wave. Converting to float results in a 0-1 array.

For this illustration it's better to position the wave in the middle of the array, avoiding boundary effects associated with convolution. Using mode='same' allows for all curves to be plotted together. Also, don't forget to divide the output of convolve by sample_rate , otherwise it will grow proportionally to it with each convolution.

import numpy as np
import matplotlib.pyplot as plt
sample_rate = 100
num_samples = 500
wave = np.fromfunction(lambda i: (2*sample_rate < i) & (i < 3*sample_rate), (num_samples,)).astype(np.float)
wave1 = np.convolve(wave, wave, mode='same')/sample_rate
wave2 = np.convolve(wave1, wave, mode='same')/sample_rate
wave3 = np.convolve(wave2, wave, mode='same')/sample_rate
plt.plot(np.stack((wave, wave1, wave2, wave3), axis=1))
plt.show()

卷积

Mathematically, these are known as cardinal B-splines and as the density of Irwin–Hall distribution .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM