用python写一个FFT代码
时间: 2023-12-17 14:46:44 浏览: 109
以下是Python中的FFT代码:
```python
import numpy as np
def fft(x):
"""
FFT (Fast Fourier Transform) algorithm
"""
# Check if input is a power of 2
n = len(x)
if n == 1:
return x
if n % 2 > 0:
raise ValueError("Size of x must be a power of 2")
# Divide the signal into even and odd components
even = fft(x[::2])
odd = fft(x[1::2])
# Calculate the Fourier coefficients
factor = np.exp(-2j * np.pi * np.arange(n) / n)
return np.concatenate([even + factor[:int(n / 2)] * odd,
even + factor[int(n / 2):] * odd])
# Test the FFT function with a sine wave
x = np.linspace(0, 2*np.pi, 8)
y = np.sin(x)
print("Input signal: ", y)
print("FFT: ", fft(y))
```
该代码使用递归地将信号分解为偶数和奇数分量,并使用指数函数计算傅里叶系数。最后,它将偶数和奇数分量的结果合并为最终结果。
阅读全文