水平线与函数的交点

points of intersection of horizontal line with a function

我有生成以下(图像)的代码,我将如何继续检测线与函数的交点?`

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.4y = 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),您可以将其绘制在图表上。