谐波分析源程序

  • 格式:docx
  • 大小:16.44 KB
  • 文档页数:4

#include

#include

#include

#define N 256

#define dt 0.078125 //采样间隔0.078125ms

#define t_min 0 //一个周期采样时间下限

#define t_max 20 //一个周期采样时间上限

#define PI 3.14159265358979323846264338327 //圆周率

#define size_x 256 //输入序列X[N]的大小,在本程序中仅限2的次幂

typedef struct //定义复数类型

{

double real;

double img;

}complex;

complex x[N], *W; //x[N]:FFT输入序列,*W:FFT变换核

int U_t(double t) //返回每个t ms对应的U值

{

t=t-(long)(t)/20*20;

if(t>=4&&t<=6)

{

return 100;

}

else if(t>=14&&t<=16)

{

return -100;

}

else

{

return 0;

}

}

void add(complex a,complex b,complex *c) //复数加法

{

c->real=a.real+b.real;

c->img=a.img+b.img; }

void mul(complex a,complex b,complex *c) //复数乘法

{

c->real=a.real*b.real - a.img*b.img;

c->img=a.real*b.img + a.img*b.real;

}

void sub(complex a,complex b,complex *c) //复数减法

{

c->real=a.real-b.real;

c->img=a.img-b.img;

}

void change() //变址计算,将x(n)码位倒置

{

complex temp;

unsigned short i=0,j=0,k=0;

double t;

for(i=0;i

{

k=i;j=0;

t=(log(size_x)/log(2));

while( (t--)>0 )

{

j=j<<1;

j|=(k & 1);

k=k>>1;

}

if(j>i)

{

temp=x[i];

x[i]=x[j];

x[j]=temp;

}

}

}

void initW() //初始化变换核

{

int i;

W=(complex *)malloc(sizeof(complex) * size_x);

for(i=0;i

{

W[i].real=cos(2*PI/size_x*i);

W[i].img=-1*sin(2*PI/size_x*i);

} }

void fft() //快速傅里叶变换

{

int i=0,j=0,k=0,l=0;

complex up,down,product;

change();

for(i=0;i< log(size_x)/log(2) ;i++)

{ /*一级蝶形运算*/

l=1<

for(j=0;j

{ /*一组蝶形运算*/

for(k=0;k

{ /*一个蝶形运算*/

mul(x[j+k+l],W[size_x*k/2/l],&product);

add(x[j+k],product,&up);

sub(x[j+k],product,&down);

x[j+k]=up;

x[j+k+l]=down;

}

}

}

}

int main()

{

double t,sum=0,square_sum=0,average,effective; //t:时间,average:平均值,effective:有效值

long count=0;

for(t=t_min;t

{

count++;

sum+=U_t(t);

square_sum+=U_t(t)*U_t(t);

}

average=sum/count;

effective=sqrt(square_sum/count);

printf("平均值:%f,有效值:%f\n***************************************************\n*******************谐波有效值**********************\n***************************************************\n",average,effective);

for(t=t_min,count=0;count

{

x[count].real=U_t(t); x[count].img=0;

}

initW();

fft();

for(count=1;count<=15;count++)

{

printf("第%d次谐波的有效值------%f\n",count,sqrt(x[count].real*x[count].real+x[count].img*x[count].img));

}

}