如何在Python中找到两条线段的交点?

如何在Python中找到两条线段的交点?,python,python-3.x,data-analysis,equation-solving,Python,Python 3.x,Data Analysis,Equation Solving,我有一个自变量x和两个因变量y1和y2的数据,如下所示: x y1 y2 -1.5 16.25 1.02 -1.25 17 1.03 -1 15 1.03 -0.75 9 1.09 -0.5 5.9 1.15 -0.25 5.2 1.17 0 4.77 1.19 +0.25 3.14 1.35 +0.5 2.5 1.54 +0.75 2.21

我有一个自变量x和两个因变量y1和y2的数据,如下所示:

 x      y1      y2
-1.5    16.25   1.02
-1.25   17      1.03
-1      15      1.03
-0.75   9       1.09
-0.5    5.9     1.15
-0.25   5.2     1.17
 0      4.77    1.19
+0.25   3.14    1.35
+0.5    2.5     1.54
+0.75   2.21    1.69
+1      1.91    1.96
+1.25   1.64    2.27
+1.5    1.52    2.56
+1.75   1.37    3.06
+2      1.24    4.12
+2.25   1.2     4.44
+2.5    1.18    4.95
+2.75   1.12    6.49
+3      1.07    10

因此,这里的
x的值,其中y1=y2
+1
附近。如何在python中读取数据并进行计算?

简单的解决方案如下所示:

txt = """-1.5    16.25   1.02
-1.25   17      1.03
-1      15      1.03
-0.75   9       1.09
-0.5    5.9     1.15
-0.25   5.2     1.17
 0      4.77    1.19
+0.25   3.14    1.35
+0.5    2.5     1.54
+0.75   2.21    1.69
+1      1.91    1.96
+1.25   1.64    2.27
+1.5    1.52    2.56
+1.75   1.37    3.06
+2      1.24    4.12
+2.25   1.2     4.44
+2.5    1.18    4.95
+2.75   1.12    6.49
+3      1.07    10"""

import numpy as np
# StringIO behaves like a file object, use it to simulate reading from a file
from StringIO import StringIO   

x,y1,y2=np.transpose(np.loadtxt(StringIO(txt)))
p1 = np.poly1d(np.polyfit(x, y1, 1))
p2 = np.poly1d(np.polyfit(x, y2, 1))
print 'equations: ',p1,p2

#y1 and y2 have to be equal for some x, that you solve for :
#  a x+ b = c x + d  --> (a-c) x= d- b

a,b=list(p1)
c,d=list(p2)
x=(d-b)/(a-c)
print 'solution x= ',x
输出:

equations:   
-3.222 x + 7.323  
1.409 x + 1.686
solution x=  1.21717324767
然后你画出“线”:

import matplotlib.pyplot as p
%matplotlib inline
p.plot(x,y1,'.-')
p.plot(x,y2,'.-')

你会发现你不能用线性假设,只能用一些片段

x,y1,y2=np.transpose(np.loadtxt(StringIO(txt)))
x,y1,y2=x[8:13],y1[8:13],y2[8:13]
p1 = np.poly1d(np.polyfit(x, y1, 1))
p2 = np.poly1d(np.polyfit(x, y2, 1))
print 'equations: ',p1,p2
a,b=list(p1)
c,d=list(p2)
x0=(d-b)/(a-c)
print 'solution x= ',x0
p.plot(x,y1,'.-')
p.plot(x,y2,'.-')
输出:

equations:   
-1.012 x + 2.968  
1.048 x + 0.956
solution x=  0.976699029126

即使是现在,你也可以通过多留下两个点来提高(看起来非常线性,但对于一些点来说这可能是巧合)

输出:

equations:   
-1.152 x + 3.073  
1.168 x + 0.806
solution x=  0.977155172414


可能更好的方法是使用更多的点并应用二阶插值
np.poly1d(np.polyfit(x,y1,2))
,然后求解两个二阶多项式的等式,我将其作为练习(二次方程)留给读者。

看起来像是一个赋值,你能展示一下你已经尝试过的东西吗?@SiddharthGupta这不是任务。添加我正在处理的问题的简化。我在Excel中用简单的折线图直观地完成了这项工作。希望将其转换为代码。也许使用matplotlib和绘图只是为了好玩,你能分享这些数据呈现的是什么样的实验吗?
equations:   
-1.152 x + 3.073  
1.168 x + 0.806
solution x=  0.977155172414