python - 在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()
有时输出看起来就像它应该的那样,例如 在这个屏幕截图中。但是,在其他时候,我会获得不想要的输出,例如在这个中。有人可以演示如何解决这个问题吗?谢谢你。
解决方案
我想建议您增加时间离散化或简单地根据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=3
和f1=200
和f2=400
Hz :
对于您有问题的情况f1=520
和f2=750
Hz:
奖励:如果您想自动计算最小n_T
周期数以显示两个振荡组件之间的唯一交叉点的确切数量。首先,将用户输入f1
和f2
从浮点数转换为整数,然后找到它们之间的最小公倍数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=250
和f2=300
Hz,n_T=1500/300=5
它将给出:
推荐阅读
- php - 避免使用 PHP 进行 URL 转换
- json - Firebase 托管重定向除一个文件之外的所有内容
- apache-kafka - 使用应用程序重置工具时,Kafka 状态存储会发生什么情况?
- python - Jupiter Notebook 无法封装folium
- react-native - 当使用 Mocha 单元 React-native 测试文件时,它给出了错误的意外提示
- javascript - DOM 事件在没有箭头功能的情况下不起作用
- javascript - ReactJS randomly Unexpected token '<'
- html - 寻找对html表单动作属性的更深入理解
- netsuite - http.get 和 http.post 通过预定脚本 Netsuite 中的错误 - 错误:在对象中找不到函数 post
- python - 我如何使用熊猫导出每行图像