points of intersection of horizontal line with a function [duplicate]

烂漫一生 提交于 2020-01-26 04:46:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!