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屋!