Dmitry Baranovskiy

Distance to an Ellipse 29·MAY·23

Distance from an arbitrary point to an ellipse.

I had a task to find out the distance from a given ellipse to a given point and my search for a solution didn’t produced any acceptable results. The other way to formulate the task might be “How to find the closest point on the given ellipse to the given point”. I was digging it for myself and managed to solve the problem (kind of). I would like to share this here for my future references and in hope that it might help somebody as well.

Lets start from the parmetric equation of an ellipse.

$$x(t)=r_1\cos t$$ $$y(t)=r_2\sin t$$

If we introduce \(v(t)=\sqrt{(x'(t))^2+(y'(t))^2}\), then the equation of the offset curve at distance \(d\) from the ellipse will look like this:

$$x_1(t)=x(t)+d\frac{y'(t)}{v(t)}$$ $$y_1(t)=y(t)+d\frac{x'(t)}{v(t)}$$

We assume that our point of interest is positioned on the offset curve. Namely at coordinates \((x_1(t),y_1(t))\). In this case, if we can find \(t\), we can find the distance \(d\). To do so we can express \(d\) from both equations:

$$\frac{(x_1(t)-x(t))v(t)}{y'(t)}=\frac{(y(t)-y_1(t))v(t)}{x'(t)}.$$

We can substitute coordinates of our point as \(X=x_1(t)\) and \(Y=y_1(t)\) and do a bit of rearrangment.

$$Xx'(t)-x(t)x'(t)+Yy'(t)-y(t)y'(t)=0.$$

If we expand the functions we will get this:

$$Yr_{2}\cos t-Xr_{1}\sin t+\left(r_{1}^{2}-r_{2}^{2}\right)\sin t\cos t=0.$$

One way to solve this with \(\alpha=\tan\frac{t}{2}\) substitution:

$$ -Yr_{2}\alpha^4+\left(2r_{2}^{2}-2r_{1}^{2}-2Xr_{1}\right)\alpha^3+\left(2r_{1}^{2}-2r_{2}^{2}-2Xr_{1}\right)\alpha+Yr_{2}=0 $$

One rearrangment later:

$$ \alpha^{4}+\frac{2r_{2}^{2}-2r_{1}^{2}-2Xr_{1}}{-Yr_{2}}\alpha^{3}+\frac{2r_{1}^{2}-2r_{2}^{2}-2Xr_{1}}{-Yr_{2}}\alpha-1=0 $$

This polynomial was solved with Newton’s method. May be there is a smarter way to do this, but Newton’s method works just fine, as you can see in the demo above.