Skip to content

Instantly share code, notes, and snippets.

@mkolod
Created July 7, 2021 02:31
Show Gist options
  • Save mkolod/4bec915ed39c3b89de1daa10d0c76ee7 to your computer and use it in GitHub Desktop.
Save mkolod/4bec915ed39c3b89de1daa10d0c76ee7 to your computer and use it in GitHub Desktop.
DFT / IDFT
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import scipy"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def dft(x):\n",
" lenx = len(x)\n",
" y = np.zeros(lenx, dtype=np.complex)\n",
" for i in range(lenx):\n",
" for j in range(lenx):\n",
" y[i] += x[j] * np.exp(-2j*np.pi*i*j/len(x))\n",
" return y\n",
"\n",
"def idft(x):\n",
" lenx = len(x)\n",
" y = np.zeros(lenx, dtype=np.complex)\n",
" for i in range(lenx):\n",
" for j in range(lenx):\n",
" y[i] += 1/lenx * x[j] * np.exp(2j*np.pi/lenx*j*i)\n",
" return y"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.randn(1024)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"y1 = dft(x)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"y2 = scipy.fft.fft(x)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.allclose(y1, y2)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"x1 = idft(y1)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"x2 = scipy.fft.ifft(y2)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.allclose(x, x1)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.allclose(x, x2)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.allclose(x1, x2)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment