implementation of fft in c

Upload: lk

Post on 14-Jul-2015

190 views

Category:

Documents


3 download

DESCRIPTION

FFT, Fast Fourier Transform in C language, FFT by C.

TRANSCRIPT

Implementation of FFT in C

/*---------------------------------------------fft_test.c - demonstration program for fft.c ----------------------------------------------*/

/****************************************************************************** * This program demonstrates how to use the file fft.c to calculate an FFT * * of given time-domain samples, as well as to calculate an inverse FFT *

* (IFFT) of given frequency-domain samples. First, N complex-valued time- * * domain samples x, in rectangular form (Re x, Im x), are read from a *

* specified file; the 2N values are assumed to be separated by whitespace. * * Then, an N-point FFT of these samples is found by calling the function * fft, thereby yielding N complex-valued frequency-domain samples X in * rectangular form (Re X, Im X). Next, an N-point IFFT of these samples is * * is found by calling the function ifft, thereby recovering the original * samples x. Finally, the calculated samples X are saved to a specified * file, if desired. * * * * *

******************************************************************************/

#include #include #include "fft.c"

int main() { int i; /* generic index */

char file[FILENAME_MAX]; /* name of data file */ int N; /* number of points in FFT */

double (*x)[2]; double (*X)[2]; double dummy; FILE *fp;

/* pointer to time-domain samples */ /* pointer to frequency-domain samples */ /* scratch variable */ /* file pointer */

/* Get name of input file of time-domain samples x. */ printf("Input file for time-domain samples x(n)? "); scanf("%s", file);

/* Read through entire file to get number N of points in FFT. */ if(!(fp = fopen(file, "r"))) { printf(" File \'%s\' could not be opened!", file); exit(EXIT_FAILURE); } N=0; while(fscanf(fp, "%lg%lg", &dummy, &dummy) == 2) N++; printf("N = %d", N);

/* Check that N = 2^n for some integer n >= 1. */ if(N >= 2) { i = N; while(i==2*(i/2)) i = i/2; /* While i is even, factor out a 2. */ } /* For N >=2, we now have N = 2^n iff i = 1. */ if(N < 2 || i != 1) {

printf(", which does not equal 2^n for an integer n >= 1."); exit(EXIT_FAILURE); }

/* Allocate time- and frequency-domain memory. */ x = malloc(2 * N * sizeof(double)); X = malloc(2 * N * sizeof(double));

/* Get time-domain samples. */ rewind(fp); for(i=0; i