简体   繁体   English

在 python 中查找交点坐标

[英]finding coordinates of intersection in python

I have 3 linear line equations.我有 3 个线性线方程。

x1= np.linspace(-1,1,100)

y1= x1
y2=-x1
y3= -2*x1 +2
plt.plot(x1,y1)
plt.plot(x1,y2)
plt.plot(x1,y3)

Is there a simple and a quicker way to find the coordinates of intersection of the three lines?有没有一种简单快捷的方法来找到三条线的交点坐标?

I have tried Intersection of two graphs in Python, find the x value , and have just the x coordinates.我已经尝试过Python 中两个图的交集,找到 x 值,并且只有 x 坐标。

But in reality I have more linear equations, so the most effective way to get the (x,y) coordinates of intersection would be most helpful.但实际上我有更多的线性方程,因此获得交叉点的 (x,y) 坐标的最有效方法将是最有帮助的。

If the main purpose is to find intersections, between equations, the symbolic math library sympy could be helpful:如果主要目的是找到方程之间的交点,符号数学库sympy可能会有所帮助:

from sympy import symbols, Eq, solve

x, y = symbols('x y')
eq1 = Eq(y, x)
eq2 = Eq(y, -x)
eq3 = Eq(y, -2 * x + 2)
print(solve([eq1, eq2]))
print(solve([eq1, eq3]))
print(solve([eq2, eq3]))

Output: Output:

{x: 0, y: 0}
{x: 2/3, y: 2/3}
{x: 2, y: -2}

To find interpolated intersections between numpy arrays, you can use the find_roots() function from this post:要查找 numpy arrays 之间的插值交点,您可以使用帖子中的find_roots() function:

from matplotlib import pyplot as plt
import numpy as np

def find_roots(x, y):
    s = np.abs(np.diff(np.sign(y))).astype(bool)
    return x[:-1][s] + np.diff(x)[s] / (np.abs(y[1:][s] / y[:-1][s]) + 1)

x1 = np.linspace(-1, 1, 100)

y1 = x1
y2 = -x1
y3 = -2 * x1 + 2
plt.plot(x1, y1, color='dodgerblue')
plt.plot(x1, y2, color='dodgerblue')
plt.plot(x1, y3, color='dodgerblue')

for ya, yb in [(y1, y2), (y1, y3), (y2, y3)]:
    x0 = find_roots(x1, ya - yb)
    y0 = np.interp(x0, x1, ya)
    print(x0, y0)
    plt.plot(x0, y0, marker='o', ls='', ms=4, color='crimson')
plt.show()

结果图

Output: Output:

[0.] [0.]
[0.66666667] [0.66666667]
[] []

Zooming in on an intersection, and marking the points of the numpy arrays, you'll notice that the intersection usually doesn't coincide with a common point of the arrays.放大交叉点,并标记 numpy arrays 的点,您会注意到交叉点通常与 arrays 的公共点不重合。 As such, an interpolation step is necessary.因此,插值步骤是必要的。

放大

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM