gpt4 book ai didi

python - 在python中绘制正弦波时的问题

转载 作者:行者123 更新时间:2023-12-04 10:13:04 25 4
gpt4 key购买 nike

我使用 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 .
有人可以演示如何解决这个问题吗?谢谢你。

最佳答案

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

1

以及您的问题案例 f1=520f2=750赫兹:

2

奖金 : 如果你想自动计算最小数 n_T周期数以显示两个振荡分量之间唯一交叉点的确切数量。首先,转换用户输入 f1f2从浮点数到整数,然后找到最小公倍数 lcm在它们之间(使用最大公约数 gcd 来自 math 的函数)并将其除以最高频率,您在这里:
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赫兹, n_T=1500/300=5这将给出:

bonus

关于python - 在python中绘制正弦波时的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61231410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com