在 python 中绘制正弦波时出现问题

Problem when graphing sine waves in python

我使用 python 编写了以下程序,以绘制不同频率的多个正弦波,并显示它们之间的交点;

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()

有时输出看起来就像它应该的那样,例如 in this screenshot。 但是,在其他时候我会得到不需要的输出,例如 in this one。 有人可以演示如何解决这个问题吗?谢谢。

我想建议您增加时间离散化或简单地根据 highest/lowest 频率的 n_T 周期数来绘制这些波,以避免采样不足问题。例如,如果您对最低频率更感兴趣,您可以按如下方式修改代码:

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: "))

n_T = float(input("Enter number of periods of lowest frequency to display: "))
t_max = n_T/min(f1,f2) # change here max or min if you want highest or lowest frequency to be represented on n_T periods

t = np.linspace(0, t_max, 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.05*t_max, 1.05*t_max, -1.5, 1.5])

plt.title("Sine Waves")
plt.xlabel("Time")
plt.ylabel("Amplitude")

plt.show()

给出 n_T=3f1=200f2=400 Hz :

对于您的问题案例 f1=520f2=750 Hz:

BONUS :如果您想自动计算最小周期数 n_T 以显示独特的确切数量两个振荡分量之间的交点。首先,将用户输入 f1f2 从浮点数转换为整数,然后找到它们之间的最小公倍数 lcm(使用来自 [=23= 的最大公约数 gcd 函数]) 然后除以最高频率,这里是:

from math import gcd
def lcm(a,b):
    """
    Compute the lowest common multiple of a and b
    """
    return a*b/gcd(a,b)

# minimum of n_T periods to visualize every unique intersections of waves
n_T = lcm(f1,f2)/max(f1,f2)

例如 f1=250f2=300 Hz,n_T=1500/300=5 将给出: