python写一个5阶IIR滤波器
时间: 2024-03-20 22:43:34 浏览: 11
以下是一个使用 Python 实现的 5 阶 IIR 滤波器示例:
```python
class IIRFilter(object):
def __init__(self, a_coeffs, b_coeffs):
self.a_coeffs = a_coeffs
self.b_coeffs = b_coeffs
self.memory = [0] * (len(self.b_coeffs) - 1)
def filter(self, input):
output = self.b_coeffs[0] * input + self.memory[0]
for i in range(1, len(self.b_coeffs)):
self.memory[i-1] = self.b_coeffs[i] * input - self.a_coeffs[i] * output + self.memory[i]
return output
```
使用方法:
```python
# 创建一个 5 阶低通滤波器
a_coeffs = [1.0, -3.956, 5.857, -3.857, 0.956]
b_coeffs = [0.000088, 0.000441, 0.000882, 0.000882, 0.000441, 0.000088]
filter = IIRFilter(a_coeffs, b_coeffs)
# 对输入信号进行滤波
input = 0.5
output = filter.filter(input)
```
在这个示例中,我们创建了一个 5 阶低通 IIR 滤波器,它的传递函数为:
$$H(z) = \frac{0.000088 + 0.000441z^{-1} + 0.000882z^{-2} + 0.000882z^{-3} + 0.000441z^{-4} + 0.000088z^{-5}}{1 - 3.956z^{-1} + 5.857z^{-2} - 3.857z^{-3} + 0.956z^{-4}}$$
其中 $a_1 = -3.956$,$a_2 = 5.857$,$a_3 = -3.857$,$a_4 = 0.956$,$b_0 = 0.000088$,$b_1 = 0.000441$,$b_2 = 0.000882$,$b_3 = 0.000882$,$b_4 = 0.000441$,$b_5 = 0.000088$。在 `filter` 方法中,我们使用差分方程来实现滤波器的输出,其中 `memory` 数组存储了滤波器的状态(历史输出值)。
注意:这只是一个简单的示例,实际应用中需要根据具体需求选择合适的滤波器类型、阶数和系数。