Responsive Navbar with Google Search
☰ Menu
Home
Python
LaTeX
GNUPlot
Arduino
Feedback
Contact Us
Fourier Series: Triangular Wave
Fourier Series
Square Wave
Triangular Wave
Sawtooth Wave
Triangular Wave: Program 1
plotting the Fourier series approximation of a triangular wave signal
import numpy as np import matplotlib.pyplot as plt from scipy import signal from scipy.integrate import quad x_ = np.linspace(-20, 20, 10000) T = 10 # Time period n2 = 10 # Number of Harmonics n1 = n2 + 1 # Define the square wave function def f(x): return signal.sawtooth(2 * np.pi * (1/T) * x, 0.5) # Define a0 a0, _ = quad(lambda x: f(x), -T/2, T/2) a0 = (2/T) * a0 print('a0', a0) # Define an, bn def integrand_an(x, n): return f(x) * np.cos(n * 2 * np.pi * x / T) def integrand_bn(x, n): return f(x) * np.sin(n * 2 * np.pi * x / T) anm = [(2/T) * quad(lambda x: integrand_an(x, i), -T/2, T/2)[0] for i in range(0, n1)] bnm = [(2/T) * quad(lambda x: integrand_bn(x, i), -T/2, T/2)[0] for i in range(0, n1)] print('an', anm) print('bn', bnm) # Fourier Series function def fs(x): sum = a0 / 2 for i in range(1, n1): sum += bnm[i] * np.sin(i * 2 * np.pi * x / T) + anm[i] * np.cos(i * 2 * np.pi * x / T) return sum y = np.array([f(i) for i in x_]) fss = np.array([fs(i) for i in x_]) plt.plot(x_, y, color="blue", label="Signal") plt.plot(x_, fss, color="red", label="Fourier series approximation") plt.title("Fourier Series approximation number of harmonics: " + str(n2)) plt.legend() plt.savefig('plot.png')
Run Code
Output 1
Triangular Wave: Program 2
Fourier series approximation of a triangular wave signal without scipy.signal
import numpy as np import matplotlib.pyplot as plt from scipy import signal from scipy.integrate import quad x_ = np.linspace(-20, 20, 10000) T = 10 # Time period n2 = 10 # Number of Harmonics n1 = n2 + 1 # Define the square wave function def f(x): x = (x % T) / T # Normalize to [0, T) return 2 * np.abs(2 * x - 1) - 1 # Define a0 a0, _ = quad(lambda x: f(x), -T/2, T/2) a0 = (2/T) * a0 print('a0', a0) # Define an, bn def integrand_an(x, n): return f(x) * np.cos(n * 2 * np.pi * x / T) def integrand_bn(x, n): return f(x) * np.sin(n * 2 * np.pi * x / T) anm = [(2/T) * quad(lambda x: integrand_an(x, i), -T/2, T/2)[0] for i in range(0, n1)] bnm = [(2/T) * quad(lambda x: integrand_bn(x, i), -T/2, T/2)[0] for i in range(0, n1)] print('an', anm) print('bn', bnm) # Fourier Series function def fs(x): sum = a0 / 2 for i in range(1, n1): sum += bnm[i] * np.sin(i * 2 * np.pi * x / T) + anm[i] * np.cos(i * 2 * np.pi * x / T) return sum y = np.array([f(i) for i in x_]) fss = np.array([fs(i) for i in x_]) plt.plot(x_, y, color="blue", label="Signal") plt.plot(x_, fss, color="red", label="Fourier series approximation") plt.title("Fourier Series approximation number of harmonics: " + str(n2)) plt.legend() plt.savefig('plot.png') plt.show()
Run Code
Output 2