水平线与函数的交点 [英] points of intersection of horizontal line with a function
问题描述
我有这段代码会生成以下图像(图像),我将如何继续检测该线与函数的交点?
i have this code that generate the following (image), how would i proceed to detect the intersections of the line with the 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
的索引.
You can use the following expression to get the indices of the array t
that is closest to the intersection points.
idx = np.argwhere(np.diff(np.sign(y - func))).flatten()
此表达式选择列表中符号变化的索引.但是,这仅是真实交点的近似值.减小t
的步长以提高精度.
This expression selects indices where there is a change of sign in the list. However, this is only an approximation of the real intersection points. Decrease the step-size of t
to increase precision.
由于方程式相对简单,另一种方法是手工求解并实现封闭形式的绘图公式.
Since the equations are relatively simple, another way would be to solve it by hand and implement the closed-form formula for plotting.
您具有方程式y = 0.4
和y = sin(2*pi*t*f/Fs)
.交叉点的值在t
处,这样0.4 = sin(2*pi*t*f/Fs)
.解决t
有两个答案:
You have the equations y = 0.4
and y = sin(2*pi*t*f/Fs)
. Intersection points are at values of t
such that 0.4 = sin(2*pi*t*f/Fs)
. Solving for t
gives two answers:
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)
.
where k
is any integer. In short, loop through all desired integers in a given range and compute the coordinates t
using the two equations above. You will get a set of points (t,0.4)
that you can plot on your graph.
这篇关于水平线与函数的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!