Fourier series in C

chris (2002-11-04 19:52:27)
2941 views
0 replies
This is a snippet of code which I implemented when designing an optoelectronic displacement transducer whilst at Hewlett Packard in Bristol. The source data is based on an error profile collected during a callibration process. The context might be inappropriate for your own application, but the algorithms still remain the same.. steal if you find it useful !
/*calculate amplitude of DC component in errfile.dat*/
open_cosfile_write();
open_sinfile_write();
open_errfile_read();
for(indicator=0;indicator<VALUES;indicator++){
	fscanf( errfile,"%lf", &fx );
	delimeter=getc(errfile);		//kill delimeter
	amplitude+=fx;
}
fcloseall();
amplitude=amplitude/VALUES;
printf("namplitude of DC component is %f",amplitude);
harmonics[0]=amplitude;

/*calculate amplitude of subsequent frequency components in errfile.dat*/
for(n=1;n<=20;n++){
	cosex_tot=0;
	sinex_tot=0;
	open_cosfile_write();
	open_sinfile_write();
	open_errfile_read();
	for(indicator=0;indicator<=VALUES;indicator++){
		fscanf( errfile,"%lf", &fx );
		delimeter=getc(errfile);		//kill delimeter
		x=((360*(float)indicator)/VALUES);
		cosex=cos(n*( (x*M_PI)/180 ));
		sinex=sin(n*( (x*M_PI)/180 ));
		fxcosex=fx*cosex;
		fxsinex=fx*sinex;
		cosex_tot+=fxcosex;
		sinex_tot+=fxsinex;
//for debug	printf("ntotal cos component: %lf, total sin component: %lf",cosex_tot, sinex_tot);
		amplitude=(((2/(float)VALUES))*(sqrt((cosex_tot*cosex_tot)+(sinex_tot*sinex_tot))));
	}
	fcloseall();
	harmonics[n]=amplitude;
}
open_fouresults_write();
printf("nthese are the frequency component amplitudes:");
for(indicator=0;indicator<20;indicator++){
	printf("t%lf",harmonics[indicator]);
	fprintf(fouresults,"%lfn",harmonics[indicator]);
}
getch();
fprintf(fouresults,"nnn");
comment