这个问题在这里已有答案:
我有这个代码生成以下(图像),我将如何继续检测线与功能的交叉点?`
import numpy as np
import matplotlib.pyplot as plt
y = 0.4*np.ones(100)
x = np.arange(0, 100)
t = np.linspace(0,100,100)
Fs = 6000
f = 200
func = np.sin(2 * np.pi * f * t / Fs)
idx = np.where(func == y) # how i think i should do to detect intersections
print(idx)
plt.plot(x, y) # the horizontal line
plt.plot(t,func) # the function
plt.show()
您可以使用以下表达式来获取最接近交叉点的数组t
的索引。
idx = np.argwhere(np.diff(np.sign(y - func))).flatten()
此表达式选择列表中符号更改的索引。但是,这只是实际交叉点的近似值。减小t
的步长以提高精度。
由于方程式相对简单,另一种方法是手工求解并实现封闭形式的绘图公式。
你有方程y = 0.4
和y = sin(2*pi*t*f/Fs)
。交叉点的值为t
,使得0.4 = sin(2*pi*t*f/Fs)
。解决t
给出了两个答案:
t = (arcsin(0.4) + 2*pi*k) / (2*pi*f/Fs)
t = (pi - arcsin(0.4) + 2*pi*k) / (2*pi*f/Fs)
其中k
是任何整数。简而言之,循环遍历给定范围内的所有所需整数,并使用上面的两个等式计算坐标t
。您将获得一组点(t,0.4)
,您可以在图表上绘制。