I've written the following program using python in order to graph multiple sine waves of different frequencies, as well as display the points of intersection between them;
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
fig = plt.figure()
ax = plt.axes()
f1 = float(input("Enter first frequency: "))
f2 = float(input("Enter second frequency: "))
t = np.linspace(0, 10, 1000)
y1 = np.sin(2*np.pi*f1*t)
y2 = np.sin(2*np.pi*f2*t)
plt.plot(t,y1, color = "firebrick", label = "sin({}Hz)".format(f1))
plt.plot(t,y2, color = "teal", label = "sin({}Hz)".format(f2))
plt.axhline(y = 0, color = "grey", linestyle = "dashed", label = "y = 0")
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
plt.plot(t[idx], y1[idx], 'k.')
plt.legend(loc = "best", frameon=True, fancybox = True,
shadow = True, facecolor = "white")
plt.axis([-0.5, 10.5, -1.5, 1.5])
plt.title("Sine Waves")
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.show()
Sometimes the output looks just as it's supposed to, for example in this screenshot. However, at other times i obtain an undesired output such as in this one. Could someone demonstrate how to fix this problem? Thank you.
I would like to suggest you to increase your time discretization or simply plot these waves in terms of number of
n_Tperiods of the highest/lowest frequency to avoid undersampling problems. For instance, if you more interested in the lowest frequency you could modified your code as follows:which gives for
n_T=3andf1=200andf2=400Hz :and for your problematic case
f1=520andf2=750Hz:BONUS : if you want to compute automatically the minimum number
n_Tof periods to display the exact number of unique intersections between the two oscillating components. First, convert user inputsf1andf2from floats to integers, then find the lowest common multiplelcmbetween them (using greatest common divisorgcdfunction frommath) and divide it by the highest frequency, here you are:for instance for
f1=250andf2=300Hz,n_T=1500/300=5which will give: