问题
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()
回答1:
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()
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.
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)
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.
来源:https://stackoverflow.com/questions/55460341/points-of-intersection-of-horizontal-line-with-a-function