簡體   English   中英

在 python 中查找交點坐標

[英]finding coordinates of intersection in python

我有 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)

有沒有一種簡單快捷的方法來找到三條線的交點坐標?

我已經嘗試過Python 中兩個圖的交集,找到 x 值,並且只有 x 坐標。

但實際上我有更多的線性方程,因此獲得交叉點的 (x,y) 坐標的最有效方法將是最有幫助的。

如果主要目的是找到方程之間的交點,符號數學庫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:

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

要查找 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:

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

放大交叉點,並標記 numpy arrays 的點,您會注意到交叉點通常與 arrays 的公共點不重合。 因此,插值步驟是必要的。

放大

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM