在C語言中,要實現傅里葉變換,你可以使用FFTW(Fastest Fourier Transform in the West)庫。下面是一個簡單的示例,展示了如何使用FFTW庫進行一維和二維傅里葉變換。
首先,確保已經安裝了FFTW庫。在Debian/Ubuntu系統上,可以使用以下命令安裝:
sudo apt-get install libfftw3-dev
接下來,創建一個名為fourier_transform.c
的C文件,并添加以下代碼:
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
#include<complex.h>
#include <fftw3.h>
void one_dimensional_fourier_transform(int n, double *input, double complex *output) {
fftw_plan plan = fftw_plan_dft_r2c_1d(n, input, output, FFTW_ESTIMATE);
fftw_execute(plan);
fftw_destroy_plan(plan);
}
void two_dimensional_fourier_transform(int nx, int ny, double **input, double complex **output) {
fftw_plan plan = fftw_plan_dft_r2c_2d(nx, ny, *input, *output, FFTW_ESTIMATE);
fftw_execute(plan);
fftw_destroy_plan(plan);
}
int main() {
int n = 8;
double input[] = {1, 2, 3, 4, 5, 6, 7, 8};
double complex output[n];
one_dimensional_fourier_transform(n, input, output);
printf("One-dimensional Fourier transform:\n");
for (int i = 0; i < n; i++) {
printf("%d: %g + %gi\n", i, creal(output[i]), cimag(output[i]));
}
int nx = 4, ny = 4;
double **input_2d = (double **)malloc(nx * sizeof(double *));
double complex **output_2d = (double complex **)malloc(nx * sizeof(double complex *));
for (int i = 0; i < nx; i++) {
input_2d[i] = (double *)malloc(ny * sizeof(double));
output_2d[i] = (double complex *)malloc(ny * sizeof(double complex));
for (int j = 0; j < ny; j++) {
input_2d[i][j] = i * j;
}
}
two_dimensional_fourier_transform(nx, ny, input_2d, output_2d);
printf("\nTwo-dimensional Fourier transform:\n");
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
printf("(%d, %d): %g + %gi\n", i, j, creal(output_2d[i][j]), cimag(output_2d[i][j]));
}
}
// Free allocated memory
for (int i = 0; i < nx; i++) {
free(input_2d[i]);
free(output_2d[i]);
}
free(input_2d);
free(output_2d);
return 0;
}
編譯并運行此程序:
gcc -o fourier_transform fourier_transform.c -lfftw3 -lm
./fourier_transform
這將輸出一維和二維傅里葉變換的結果。注意,這個示例僅用于演示目的,實際應用中可能需要對輸入數據和輸出結果進行更復雜的處理。