巴特沃斯滤波器 c语言
时间: 2023-10-26 21:20:09 浏览: 214
巴特沃斯滤波器c语言.doc
5星 · 资源好评率100%
巴特沃斯滤波器是数字信号处理中常用的一种滤波器,可以实现对数字信号的滤波。下面是一个巴特沃斯滤波器的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_ORDER 8
typedef struct {
int order;
double a[MAX_ORDER + 1];
double b[MAX_ORDER + 1];
} ButterworthFilter;
void butterworthFilterInit(ButterworthFilter *filter, int order, double cutoff_freq, double sample_rate) {
int i;
double theta;
double q;
double a[MAX_ORDER + 1];
double b[MAX_ORDER + 1];
double alpha[MAX_ORDER + 1];
double beta[MAX_ORDER + 1];
if (order < 1 || order > MAX_ORDER) {
fprintf(stderr, "Error: Invalid filter order (%d)\n", order);
exit(EXIT_FAILURE);
}
if (cutoff_freq <= 0.0 || cutoff_freq >= sample_rate / 2.0) {
fprintf(stderr, "Error: Invalid cutoff frequency (%g)\n", cutoff_freq);
exit(EXIT_FAILURE);
}
theta = M_PI * cutoff_freq / sample_rate;
q = 1.0 / tan(theta);
for (i = 0; i <= order; i++) {
alpha[i] = sin((2.0 * i + 1.0) * M_PI / (2.0 * order));
beta[i] = 1.0 + q * alpha[i];
}
b[0] = q / beta[0];
a[0] = 1.0;
for (i = 1; i <= order; i++) {
b[i] = q * alpha[i] / beta[i];
a[i] = (q * alpha[i - 1]) / beta[i] + (1.0 - q / beta[i - 1]);
}
filter->order = order;
for (i = 0; i <= order; i++) {
filter->a[i] = a[i];
filter->b[i] = b[i];
}
}
double butterworthFilterApply(ButterworthFilter *filter, double x) {
int i;
double y;
y = filter->b[0] * x + filter->b[1] * filter->a[0] - filter->a[1] * filter->b[0];
for (i = 2; i <= filter->order; i++) {
y = filter->b[i - 1] * filter->a[i - 2] + filter->b[i] * filter->a[i - 1] - filter->a[i] * y;
}
return y;
}
int main(void) {
int i;
ButterworthFilter filter;
double cutoff_freq = 1000.0;
double sample_rate = 44100.0;
double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
double y;
butterworthFilterInit(&filter, 4, cutoff_freq, sample_rate);
for (i = 0; i < sizeof(x) / sizeof(x[0]); i++) {
y = butterworthFilterApply(&filter, x[i]);
printf("%g -> %g\n", x[i], y);
}
return EXIT_SUCCESS;
}
```
该实现中定义了一个ButterworthFilter结构体来存储滤波器的参数,其中包括滤波器的阶数、系数a和系数b。在初始化函数butterworthFilterInit中,根据滤波器的阶数、截止频率和采样率计算出系数a和系数b。在应用滤波器时,将输入信号x作为参数传入butterworthFilterApply函数中,计算得到输出信号y,并返回给调用者。
在main函数中,首先初始化一个ButterworthFilter结构体并设置滤波器的阶数、截止频率和采样率。然后将输入信号x作为参数传入butterworthFilterApply函数中,得到输出信号y,并打印输出。
阅读全文