'''pointLineDist.py ''' import math def pointLineDist(px, py, x0, y0, x1, y1): ''' Return (u, v) where u is the fraction of the way between the line seg endpoints that the perpendicular through P meets the segment. and where v is the distance from the point to the line. ''' # My approach: translate x0, y0 to the origin. x1n = x1-x0 y1n = y1-y0 pxn = px-x0 pyn = py-y0 # pretend to rotate the line segment to line up with the Y axis. hypot = math.sqrt(x1n*x1n+y1n*y1n) costheta = y1n / hypot sintheta = x1n / hypot print "(costheta,sintheta)="+str((costheta,sintheta)) # apply that rotation to the translated P pxnr = costheta*pxn - sintheta*pyn pynr = sintheta*pxn + costheta*pyn # determine u and v u = pynr / hypot v = pxnr return (u,v) def test(): x0 = 1.0 y0 = 1.0 x1 = 2.0 y1 = 2.0 px = 2.5 py = 1.0 print pointLineDist(px,py,x0,y0,x1,y1) #test()