### Code: The Distance from Point to Line Segment

上周提到的“点到线段的距离”问题，我的Python Code是这样的：

import math

def p2s( a, b, p ):

dX = b[0] - a[0]

dY = b[1] - a[1]

segmentLen = math.sqrt( dX * dX + dY * dY )

halfLen = segmentLen / 2

pX = p[0] - a[0]

pY = p[1] - a[1]

if segmentLen < 1E-6:

return math.sqrt( pX * pX + pY * pY )

newX = abs( ( pX * dX + pY * dY ) / segmentLen - halfLen )

newY = abs( - pX * dY + pY * dX ) / segmentLen

if newX > halfLen:

newX = newX - halfLen

return math.sqrt( newX * newX + newY * newY )

else:

return newY

a = ( 1, 1 )

b = ( 4, 5 )

p = ( 0, 5 )

print p2s( a, b, p )

## 3 Comments:

thanks :)

Big thanks to you :-) That what i

wanted, you saved my night-dreams

;-)

thanks for sharing the code.I really interested to learn on how to measure the distance from point to line segment.

Post a Comment

<< Home