c++实现巴特沃斯带通滤波器代码
时间: 2023-05-30 08:07:52 浏览: 447
以下是C语言实现巴特沃斯带通滤波器的代码:
```c
#include <math.h>
#define PI 3.14159265358979323846
// 巴特沃斯带通滤波器
// fs: 采样率
// f1: 通带下限频率
// f2: 通带上限频率
// n: 滤波器阶数
// x: 输入信号
// y: 输出信号
void butterworth_bandpass_filter(double fs, double f1, double f2, int n, double *x, double *y, int len) {
double w1 = 2 * PI * f1 / fs;
double w2 = 2 * PI * f2 / fs;
double bw = w2 - w1;
double c = cos(bw / (2 * n));
double s = sin(bw / (2 * n));
double alpha = s / (2 * c);
double beta = sqrt(pow(alpha, 2) + pow(1 / c, 2));
double gain = pow(beta, n);
double a0 = 1;
double a1 = 2 * cos(w1 + w2) / (2 + alpha * (1 - gain));
double a2 = (alpha * (1 - gain) - 2 * c) / (1 + alpha * (1 - gain));
double b1 = -2 * cos(w1 + w2) / (1 + alpha * (1 - gain));
double b2 = (1 - alpha * (1 - gain) - 2 * c) / (1 + alpha * (1 - gain));
double x1 = 0, x2 = 0, y1 = 0, y2 = 0;
for (int i = 0; i < len; i++) {
double x0 = x[i];
double y0 = (a0 * x0 + a1 * x1 + a2 * x2 - b1 * y1 - b2 * y2) / gain;
x2 = x1;
x1 = x0;
y2 = y1;
y1 = y0;
y[i] = y0;
}
}
```
使用方法:
```c
#include <stdio.h>
int main() {
double fs = 1000; // 采样率
double f1 = 50; // 通带下限频率
double f2 = 200; // 通带上限频率
int n = 4; // 滤波器阶数
// 构造一个测试信号,包含 50Hz 和 200Hz 两个频率成分
int len = 1000;
double x[len];
for (int i = 0; i < len; i++) {
x[i] = sin(2 * PI * 50 * i / fs) + sin(2 * PI * 200 * i / fs);
}
// 进行巴特沃斯带通滤波
double y[len];
butterworth_bandpass_filter(fs, f1, f2, n, x, y, len);
// 输出结果
for (int i = 0; i < len; i++) {
printf("%f\n", y[i]);
}
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![nexe](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)