用Python编程,对方波信号做傅里叶级数重构,根据用户输入的最大谐波次数,逐次增加谐 波次数,动态绘制原始信号和重构信号的波形图。
时间: 2024-12-09 08:18:39 浏览: 22
在Python中,你可以使用matplotlib库来绘制图形,numpy处理数值计算,而scipy.signal库则包含傅立叶变换的相关函数。下面是一个简单的步骤说明:
1. 导入所需库:
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import periodogram, reconstruct
```
2. 定义方波信号生成函数:
```python
def generate_square_wave(frequency, sample_rate, max_harmonics):
t = np.arange(0, 1, 1/sample_rate)
signal = np.where(np.abs(np.sin(2*np.pi*frequency*t)) > 0.5, 1, -1)
return t, signal
```
3. 获取用户输入并生成信号:
```python
sample_rate = float(input("请输入采样率:"))
max_harmonics = int(input("请输入最大谐波次数:"))
t, square_wave = generate_square_wave(1, sample_rate, max_harmonics)
```
4. 对信号做傅里叶变换:
```python
frequencies, Pxx = periodogram(square_wave, fs=sample_rate)
```
5. 重构信号:
```python
reconstructed_signal = reconstruct(Pxx[:max_harmonics+1], frequencies[:max_harmonics+1])
```
6. 绘制原始信号和重构信号波形图:
```python
plt.figure(figsize=(10, 6))
plt.plot(t, square_wave, label="Original Signal")
plt.plot(t, reconstructed_signal, label="Reconstructed Signal (Max {} harmonics)".format(max_harmonics))
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Square Wave Reconstruction')
plt.legend()
plt.show()
```
7.
阅读全文