from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from datetime import date
date.today()
author = "kyubyong. https://github.com/Kyubyong/numpy_exercises"
np.__version__

Complex NumbersΒΆ

Solutions using np.angle(), .real, .imag, and np.conjugate() to manipulate complex number components.

Q1. Return the angle of a in radian.

a = 1+1j
output = np.angle(a, deg=False)
print(output)

Q2. Return the real part and imaginary part of a.

a = np.array([1+2j, 3+4j, 5+6j])
real = a.real
imag = a.imag
print("real part=", real)
print("imaginary part=", imag)

Q3. Replace the real part of a with 9, the imaginary part with [5, 7, 9].

a = np.array([1+2j, 3+4j, 5+6j])
a.real = 9
a.imag = [5, 7, 9]
print(a)

Q4. Return the complex conjugate of a.

a = 1+2j
output = np.conjugate(a)
print(output)

Discrete Fourier TransformΒΆ

Solutions using np.fft.fft(), np.fft.ifft(), np.fft.rfft(), np.fft.irfft(), and np.fft.fftfreq() for forward/inverse DFT computation and frequency extraction.

Q5. Compuete the one-dimensional DFT of a.

a = np.exp(2j * np.pi * np.arange(8))
output = np.fft.fft(a)
print(output)

Q6. Compute the one-dimensional inverse DFT of the output in the above question.

print("a=", a)
inversed = np.fft.ifft(output)
print("inversed=", a)

Q7. Compute the one-dimensional discrete Fourier Transform for real input a.

a = [0, 1, 0, 0]
output = np.fft.rfft(a)
print(output)
assert output.size==len(a)//2+1 if len(a)%2==0 else (len(a)+1)//2

# cf.
output2 = np.fft.fft(a)
print(output2)

Q8. Compute the one-dimensional inverse DFT of the output in the above question.

inversed = np.fft.ifft(output)
print("inversed=", a)

Q9. Return the DFT sample frequencies of a.

signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=np.float32)
fourier = np.fft.fft(signal)
n = signal.size
freq = np.fft.fftfreq(n, d=1)
print(freq)

Window FunctionsΒΆ

Visualization of standard window functions (Bartlett, Blackman, Hamming, Hanning, Kaiser) used to reduce spectral leakage in Fourier analysis. The plot below compares their shapes – notice how different windows trade off between main-lobe width and side-lobe suppression.

fig = plt.figure(figsize=(19, 10))

# Hamming window
window = np.hamming(51)
plt.plot(np.bartlett(51), label="Bartlett window")
plt.plot(np.blackman(51), label="Blackman window")
plt.plot(np.hamming(51), label="Hamming window")
plt.plot(np.hanning(51), label="Hanning window")
plt.plot(np.kaiser(51, 14), label="Kaiser window")
plt.xlabel("sample")
plt.ylabel("amplitude")
plt.legend()
plt.grid()

plt.show()