SymPy
lastmod 2024-03-07created 2015-12-186 edits
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python and does not require any external libraries.
Finding the perpendicular foot (shortest distance) from a point to a line segment
import matplotlib as mpl
import matplotlib.pylab as plt
from sympy import Point, Line
p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
l1 = Line(p1, p2)
l2 = l1.perpendicular_line(p3)
p4 = l1.intersection(l2)[0]
print('Result 1:', p4)
print('Result 2:', p4.x)
print('Result 3:', p4[0])
print('Result 4:', float(p4.y))
print('Result 5:', float(p4[1]))
plt.plot([p1.x, p2.x], [p1.y, p2.y])
plt.plot(p3.x, p3.y, marker='o', color='red')
plt.plot(p4.x, p4.y, marker='o', color='blue')
#plt.show()
plt.savefig('preview.jpg')
Sympy_perpendicular_line_intersection.jpg