# -*- coding: UTF-8 -*-
# 作者：huanhuilong
# 标题：Python 傅立叶变换
# 描述：计算实数序列的离散傅立叶变换，许多机器翻译把 real 翻译成 "实际"，那都是错的！

import numpy as np
from scipy.fft import rfft, rfftfreq, irfft
import matplotlib.pyplot as plt


def wave(duration, sample_rate, freq):
    x = np.linspace(0, duration, sample_rate*duration, endpoint=False)
    w = np.sin((2 * np.pi) * freq*x)
    return x, w


def rtransform(duration, sample_rate, w):
    N = sample_rate*duration
    xf = rfftfreq(N, 1/sample_rate)
    wf = rfft(w)
    return xf, wf


def inverse_rtransform(duration, sample_rate, wf):
    w = irfft(wf)
    return w


if __name__ == "__main__":

    duration = 3
    sample_rate = 30000
    freq = 4

    # 正玄波
    x, w = wave(duration, sample_rate, freq)

    # 傅立叶变换
    xrf, wrf = rtransform(duration, sample_rate, w)

    # 傅立叶逆变换
    w2 = inverse_rtransform(duration, sample_rate, wrf)

    # 打印离散傅立叶变换图
    plt.plot(wrf)

    plt.show()
