Path: utzoo!attcan!uunet!samsung!gem.mps.ohio-state.edu!apple!sun-barr!newstop!sun!looney!dopey From: dopey%looney@Sun.COM (Can't ya tell by the name) Newsgroups: comp.misc Subject: Re: Trig question Message-ID: <128175@sun.Eng.Sun.COM> Date: 21 Nov 89 02:53:10 GMT References: <4881@cbnewsc.ATT.COM> Sender: news@sun.Eng.Sun.COM Reply-To: dopey@sun.UUCP (Can't ya tell by the name) Distribution: comp Organization: Sun Microsystems, Mountain View Lines: 87 In article <4881@cbnewsc.ATT.COM> ajaym@cbnewsc.ATT.COM (alton.jay.mitchell) writes: >> " What is the shortest distance between coordinate (a3, b3) and the line >> through coordinates (a1, b1) and (a2, b2)? " > >I didn't take the time to compute a formula, but it seems somewhat >obvious that the answer can be presented in 3 parts: > > (a1,b1)------------------(a2,b2) > >If (a3,b3) is "within" the area bounded by the perpendicular >lines through (a1,b1) and (a2,b2), then the shortest distance >is the perpendicular line from (a3,b3) to the line shown. > >Otherwise, the shortest distance is the line to one of the >2 points, depending on which "side" of the above mentioned >area (a3,b3) exists on. In nitty gritty detail (this works but may not be the BEST way): I stole this from some code I had written before and checked it over but I have not run THIS version but I hope it helps. It only computes the SQUARE of the distance because I was only looking for relative distances and finding the square root was to much over head. /* This routine computes the SQUARE of the * distance from point x,y to line l */ struct line /* format of line overlay */ { short label; /* indecates type */ long x1; /* start x */ long y1; /* start y */ long x2; /* end x */ long y2; /* end y */ }; #define SIGN(x) (((x) >= 0)? 1: -1) double hypot(); double point_line(x, y, l) int x; int y; struct line *l; { double a; /* slop of the line */ double b; /* -1 in double form */ double c; /* y intercept */ double d0; /* distance from x,y to "infinite" line */ double d1; /* length of line */ double d2; /* worst case of point to line */ double d3; /* distance from x,y to line endpoint 1 */ double d4; /* distance from x,y to line endpoint 2 */ double d; /* distance from x,y to line */ if((l->x2 - l->x1) == 0) { d0 = MIN(ABS(l->y2 - y), ABS(l->y1 - y)); } else { a = (double)(l->y2 - l->y1)/(double)(l->x2 - l->x1); b = -1; c = l->y1 - a*l->x1; d0 = (double)(a*x + b*y + c)/(double)(-1*SIGN(c)*hypot(a,b)); d0 = ABS(d0); } d1 = hypot((double)ABS(l->x2 - l->x1), (double)ABS(l->y2 - l->y1)); d2 = hypot(d0, d1); d3 = hypot((double)ABS(l->x1 - x), (double)ABS(l->y1 - y)); d4 = hypot((double)ABS(l->x2 - x), (double)ABS(l->y2 - y)); d = d0; if (d3 > d2 || d4 > d2) { d = MIN(d3,d4); } return(ABS(d)); }