在Python中两个图形的交点,找到x值 [英] Intersection of two graphs in Python, find the x value
问题描述
让0< = x< =1.我有两列f
和g
分别为5000.现在我绘图:
Let 0 <= x <= 1. I have two columns f
and g
of length 5000 respectively. Now I plot:
plt.plot(x, f, '-')
plt.plot(x, g, '*')
我想找到曲线相交的点"x".我不想找到f和g的交集. 我可以这样简单地做到:
I want to find the point 'x' where the curve intersects. I don't want to find the intersection of f and g. I can do it simply with:
set(f) & set(g)
推荐答案
您可以将np.sign
与np.diff
和np.argwhere
结合使用以获取线相交的点的索引(在这种情况下,点是[ 0, 149, 331, 448, 664, 743]
):
You can use np.sign
in combination with np.diff
and np.argwhere
to obtain the indices of points where the lines cross (in this case, the points are [ 0, 149, 331, 448, 664, 743]
):
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 1000)
f = np.arange(0, 1000)
g = np.sin(np.arange(0, 10, 0.01) * 2) * 1000
plt.plot(x, f, '-')
plt.plot(x, g, '-')
idx = np.argwhere(np.diff(np.sign(f - g))).flatten()
plt.plot(x[idx], f[idx], 'ro')
plt.show()
首先,它使用np.sign
计算f - g
和相应的符号.应用np.diff
会显示符号改变的所有位置(例如,线交叉).使用np.argwhere
可以为我们提供准确的索引.
First it calculates f - g
and the corresponding signs using np.sign
. Applying np.diff
reveals all the positions, where the sign changes (e.g. the lines cross). Using np.argwhere
gives us the exact indices.
这篇关于在Python中两个图形的交点,找到x值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!