使用Golang python C三种语言测试FFT快速傅里叶变换算法

Golang
package main

import (
    "fmt"
    "github.com/mjibson/go-dsp/fft"
)

func main() {
    res := fft.FFTReal([]float64{1, 2, 3})
    fmt.Println(len(res))
    fmt.Println(res)

    x := fft.IFFT(res)
    _ = x
    print(imag(x[0]))
}
Python
import os, time, sys
import numpy as np
import matplotlib.pyplot as plt

def p(*x): print(*x)

F1 = 52;  # 信号1频率(Hz)
F2 = 75;  # 信号2频率(Hz)

# F1 = 32;  # 信号1频率(Hz)
# F2 = 64;  # 信号2频率(Hz)

Adc = 2;  # 直流分量幅度
A1 = 3;   # 频率F1信号的幅度
A2 = 1.5; # 频率F2信号的幅度

Fs = 256; # 采样频率(Hz)
P1 = -30; # 信号1相位(度)
P2 = 90;  # 信号2相位(度)

N = 256;  # 采样点数

t= np.linspace(0, 1 - 1/N, N); # 采样时刻

# t= np.linspace(0, 1, N); # 非整周期采样

p(len(t), t.dtype)

pi = np.pi
# 信号
S = Adc+A1*np.cos(2*pi*F1*t+pi*P1/180)+A2*np.cos(2*pi*F2*t+pi*P2/180);

# plt.plot(S)
# plt.show()

fft = np.fft.fft(S)

p(len(S))

plt.plot(np.abs(fft) / (N / 2))

plt.show()
C语言
#include <stdio.h>
#include <math.h>
#include <complex.h>
 
double PI;
typedef double complex cplx;

int N = 8;

void _fft(cplx buf[], cplx out[], int n, int step)
{
    if (step < n) {
        _fft(out, buf, n, step * 2);
        _fft(out + step, buf + step, n, step * 2);
 
        for (int i = 0; i < n; i += 2 * step) {
            cplx t = cexp(-I * PI * i / n) * out[i + step];
            buf[i / 2]     = out[i] + t;
            buf[(i + n)/2] = out[i] - t;
        }
    }
}
 
void fft(cplx buf[], int n)
{
    cplx out[n];
    for (int i = 0; i < n; i++) out[i] = buf[i];
 
    _fft(buf, out, n, 1);
}
 
 
void show(const char * s, cplx buf[]) {
    printf("%s\n", s);
    for (int i = 0; i < N; i++) {
        // if (!cimag(buf[i]))
        //     printf("%g ", creal(buf[i]));
        // else
        printf("(%g, %g) \n", creal(buf[i]), cimag(buf[i]));
    }
}
 
int main()
{
    PI = atan2(1, 1) * 4;

    printf("PI %g\n", PI);

    cplx buf[] = {0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5};

    // cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0};
 
    show("Data: ", buf);
    fft(buf, N);
    show("\nFFT : ", buf);
 
    return 0;
}


发表于:2017-10-13 10:59:17

原文链接(转载请保留): http://www.multisilicon.com/blog/a25276749.html

友情链接: MICROIC
首页