# Scipy FFTpack

## 快速傅立葉變換

``````#Importing the fft and inverse fft functions from fftpackage
from scipy.fftpack import fft

#create an array with random n numbers
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

#Applying the fft function
y = fft(x)
print (y)``````

``````[ 4.50000000+0.j          2.08155948-1.65109876j -1.83155948+1.60822041j
-1.83155948-1.60822041j  2.08155948+1.65109876j]``````

``````#Importing the fft and inverse fft functions from fftpackage
from scipy.fftpack import fft
from scipy.fftpack import ifft

#create an array with random n numbers
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

#Applying the fft function
y = fft(x)
#FFT is already in the workspace, using the same workspace to for inverse transform

yinv = ifft(y)

print (yinv)``````

``[ 1.0+0.j  2.0+0.j  1.0+0.j -1.0+0.j  1.5+0.j]``

`scipy.fftpack`模塊允許計算快速傅立葉變換。 作爲一個例子，一個(嘈雜的)輸入信號可能看起來如下 -

``````import numpy as np
time_step = 0.02
period = 5.
time_vec = np.arange(0, 20, time_step)
sig = np.sin(2 * np.pi / period * time_vec) + 0.5 *np.random.randn(time_vec.size)
print (sig.size)``````

``1000``

``````from scipy import fftpack
sample_freq = fftpack.fftfreq(sig.size, d = time_step)
sig_fft = fftpack.fft(sig)
print (sig_fft)``````

``````array([
25.45122234 +0.00000000e+00j,   6.29800973 +2.20269471e+00j,
11.52137858 -2.00515732e+01j,   1.08111300 +1.35488579e+01j,
…….])``````

## 離散餘弦變換

``````from scipy.fftpack import dct
mydict = dct(np.array([4., 3., 5., 10., 5., 3.]))
print(mydict)``````

``[ 60.          -3.48476592 -13.85640646  11.3137085    6.          -6.31319305]``

``````from scipy.fftpack import dct
from scipy.fftpack import idct
d = idct(np.array([4., 3., 5., 10., 5., 3.]))
print(d)``````

``````[ 39.15085889 -20.14213562  -6.45392043   7.13341236   8.14213562
-3.83035081]``````