用python写一个fft代码
时间: 2023-08-04 22:12:32 浏览: 148
好的,以下是Python实现的FFT代码:
```python
import numpy as np
def fft(x):
N = len(x)
if N <= 1:
return x
even = fft(x[0::2])
odd = fft(x[1::2])
T = [np.exp(-2j * np.pi * k / N) * odd[k] for k in range(N // 2)]
return [even[k] + T[k] for k in range(N // 2)] + \
[even[k] - T[k] for k in range(N // 2)]
# 测试
x = np.array([1, 2, 3, 4])
X = fft(x)
print(X)
```
输出结果为:
```
[(10+0j), (-2+2j), (-2+0j), (-2-2j)]
```
其中,计算出来的X就是输入信号x的FFT结果。
相关问题
用Python写一个FFT代码
好的,以下是Python实现的FFT代码:
```python
import numpy as np
def fft(x):
N = len(x)
if N <= 1:
return x
even = fft(x[0::2])
odd = fft(x[1::2])
T = [np.exp(-2j * np.pi * k / N) * odd[k] for k in range(N // 2)]
return [even[k] + T[k] for k in range(N // 2)] + \
[even[k] - T[k] for k in range(N // 2)]
# 测试
x = np.array([1, 2, 3, 4])
X = fft(x)
print(X)
```
输出结果为:
```
[(10+0j), (-2+2j), (-2+0j), (-2-2j)]
```
其中,计算出来的X就是输入信号x的FFT结果。
用python写一个FFT代码
以下是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))
```
该代码使用递归地将信号分解为偶数和奇数分量,并使用指数函数计算傅里叶系数。最后,它将偶数和奇数分量的结果合并为最终结果。
阅读全文