Closest Point On A Circle To A Line Segment Python
I need to find the closest distance between a box and a circle, however, I realize this can be broken up into the closest distance between a line segment and a circle. Given I hav
Solution 1:
There exists a method to find the closest distance from circle to rectangle (axis-oriented here). Rectangle sides divide plane into 9 pieces. We can find what piece (central, left-top, left etc) contains circle center, and calculate needed distance. Rectangle ABCD and circle center E:
Delphi code:
//returns closest distance from circle to rectangle//0 if intersection or inclusion occurs
function CircleRectDistance(CX, CY, CR: Integer; RR: TRect): Double;
var
wh, hh, dx, dy, t, SquaredDist: Double;
begin
SquaredDist := 0;
//halfwidth and halfheight
wh := 0.5 * (RR.Right - RR.Left);
hh := 0.5 * (RR.Bottom - RR.Top);
//distances to rectangle center
dx := CX - 0.5 * (RR.Left + RR.Right);
dy := CY - 0.5 * (RR.Top + RR.Bottom);
//rectangle sides divide plane to 9 parts,
t := dx + wh;
if t < 0 then
SquaredDist := t * t
else begin
t := dx - wh;
if t > 0 then
SquaredDist := t * t
end;
t := dy + hh;
if t < 0 then
SquaredDist := SquaredDist + t * t
else begin
t := dy - hh;
if t > 0 then
SquaredDist := SquaredDist + t * t
end;
if SquaredDist < CR * CR then
Result := 0else
Result := Sqrt(SquaredDist)- CR;
end;
Solution 2:
The euclid module. Install with:
pip install euclid
Then use it like this:
>>>from euclid import *>>>circ = Circle(Point2(3., 2.), 2.)>>>line = Line2(Point2(0., 0.), Point2(-1., 1.))>>>line.distance(circ)
1.5355339059327378
Post a Comment for "Closest Point On A Circle To A Line Segment Python"