Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find a point on a circle closest to a given point

Given a point (pX, pY) and a circle with a known center (cX,cY) and radius (r), what is the shortest amount of code you can come up with to find the point on the circle closest to (pX, pY) ?

I've got some code kind of working but it involves converting the circle to an equation of the form (x - cX)^2 + (y - cY)^2 = r^2 (where r is radius) and using the equation of the line from point (pX, pY) to (cX, cY) to create a quadratic equation to be solved.

Once I iron out the bugs it'll do, but it seems such an inelegant solution.

like image 545
Matt Mitchell Avatar asked Nov 19 '08 02:11

Matt Mitchell


People also ask

How do you find the closest point to a set of points?

The closest pair is the minimum of the closest pairs within each half and the closest pair between the two halves. To split the point set in two, we find the x-median of the points and use that as a pivot. Finding the closest pair of points in each half is subproblem that is solved recursively.

How do you find a point on a circle?

Distance Formula for a Point and the Center of a Circle: d=√(x−h)2+(y−k)2 d = ( x − h ) 2 + ( y − k ) 2 , where (x, y) is the point and (h,k) is the center of the circle. This formula is derived from the Pythagorean Theorem.


2 Answers

where P is the point, C is the center, and R is the radius, in a suitable "mathy" language:

V = (P - C); Answer = C + V / |V| * R; 

where |V| is length of V.

OK, OK

double vX = pX - cX; double vY = pY - cY; double magV = sqrt(vX*vX + vY*vY); double aX = cX + vX / magV * R; double aY = cY + vY / magV * R; 

easy to extend to >2 dimensions.

like image 76
Mike Dunlavey Avatar answered Oct 01 '22 11:10

Mike Dunlavey


i would make a line from the center to the point, and calc where that graph crosses the circle oO i think not so difficult

like image 20
Johannes Schaub - litb Avatar answered Oct 01 '22 11:10

Johannes Schaub - litb