首页 > 解决方案 > 在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()

有时输出看起来就像它应该的那样,例如 在这个屏幕截图中。但是,在其他时候,我会获得不想要的输出,例如在这个中。有人可以演示如何解决这个问题吗?谢谢你。

标签: pythonnumpymatplotlibgraphsine-wave

解决方案


我想建议您增加时间离散化或简单地根据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=400Hz :

1

对于您有问题的情况f1=520f2=750Hz:

2

奖励:如果您想自动计算最小n_T周期数以显示两个振荡组件之间的唯一交叉点的确切数量。首先,将用户输入f1f2从浮点数转换为整数,然后找到它们之间的最小公倍数lcm(使用最大公约数gcd函数 frommath)并将其除以最高频率,这里你是:

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=300Hz,n_T=1500/300=5它将给出:

奖金


推荐阅读