In the following formulas, the variables are :
- : time, represented in the x-axis
- : amplitude
- : frequency
- : period =
We start by importing the numpy and matplotlib packages and defining some variables :
import matplotlib.pyplot as pp
import numpy as np
f = 1 # [Hz]
p = 1/f # period in [s]
a = 3 # amplitude; full peak-to-peak will be 2*amplitude
periods = 2 # show 2 periods
samples = 1000 # sample points (resolution of the graph)
t = np.linspace(0, periods/f, samples) # Return evenly spaced numbers over a specified interval
Sine wave
pp.plot(t, a * np.sin(2 * np.pi * f * t))
pp.grid()
Square wave
pp.plot(t, a * np.sign(np.sin(2 * np.pi * f * t)))
pp.grid()
alternative with the floor function :
pp.plot(t, a * (2 * (2*np.floor(f * t) - np.floor(2 * f * t)) + 1))
pp.grid()
Triangle wave
pp.plot(t, a * abs(((t-p/4) % p) - (p/2)) * 4 / p - a)
# '%' can be replaced by the numpy mod function :
# amplitude * abs(np.mod((t-T/4), T) - (T/2)) * 4 / T - amplitude
pp.grid()
alternative as the absolute value of a shifted sawtooth wave :
pp.plot(t, a * (4 * abs(f * t - np.floor(f * t + 1/2)) - 1))
pp.grid()
if we correct the phase offset :
pp.plot(t, a * (4 * abs(f * (t+1/4) - np.floor(f * (t+1/4) + 1/2)) - 1))
pp.grid()
Sawtooth wave
pp.plot(t, a * 2 * (f * t - np.floor(f * t + 1/2)))
pp.grid()
Inverse sawtooth
pp.plot(t, 2 * a * (np.floor(f * t - 1/2) - f * t + 1))
pp.grid()