阅读量:0
在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
这将输出一维和二维傅里叶变换的结果。注意,这个示例仅用于演示目的,实际应用中可能需要对输入数据和输出结果进行更复杂的处理。