How to write a simple python code to find the intersection point between two straight lines ?

Daidalos June 21, 2019

Example of how to write a simple python code to find the intersection point between two straight lines:

Plot the lines

import matplotlib.pyplot as plt
import numpy as np

m1, b1 = 1.0, 2.0 # slope & intercept (line 1)
m2, b2 = 4.0, -3.0 # slope & intercept (line 2)

x = np.linspace(-10,10,500)

plt.plot(x,x*m1+b1)
plt.plot(x,x*m2+b2)

plt.xlim(-2,8)
plt.ylim(-2,8)

plt.title('How to find the intersection of two straight lines ?', fontsize=8)

plt.grid(linestyle='dotted')

plt.savefig("two_straight_lines_intersection_point_01.png", bbox_inches='tight')


Find the intersection point

xi = (b1-b2) / (m2-m1)
yi = m1 * xi + b1

print('(xi,yi)',xi,yi)


returns (xi,yi) 1.6666666666666667 3.666666666666667:

Plot the intersection point

plt.scatter(xi,yi, color='black' )

plt.savefig("two_straight_lines_intersection_point_02.png", bbox_inches='tight')


Another example

import matplotlib.pyplot as plt
import numpy as np

m1, b1 = 0.1, 2.0 # slope & intercept (line 1)
m2, b2 = 2.0, -3.0 # slope & intercept (line 2)

x = np.linspace(-10,10,500)

plt.plot(x,x*m1+b1,'k')
plt.plot(x,x*m2+b2,'k')

plt.xlim(-2,8)
plt.ylim(-2,8)

plt.title('How to find the intersection of two straight lines ?', fontsize=8)

xi = (b1-b2) / (m2-m1)
yi = m1 * xi + b1

print('(xi,yi)',xi,yi)

plt.axvline(x=xi,color='gray',linestyle='--')
plt.axhline(y=yi,color='gray',linestyle='--')

plt.scatter(xi,yi, color='black' )

plt.savefig("two_straight_lines_intersection_point_03.png", bbox_inches='tight')


References

Links Site
Point d'intersection lexique.netmath.ca
Déterminer, s'il existe, le point d'intersection de 2 droites s'il existe. calculis.net
Coordonnées du point d'intersection de deux droites ilemaths.net

Licence

Activity

Google Ads