# Formula for the distance between two squares.

Picture two squares, both of side length $l$, located in a plane. I know the coordinates for both of their centers, $\vec r_i$, and the angle, $\theta_i$, between a vector pointing to an equivalent point on each one's perimeters from the center, and the $x$-axis. How can I calculate the distance between the points in each of their perimeters that are the closest?

So far I've tried to do:

$$d^2=\min_{\phi_1,\phi_2}\left(\lvert\vec r_1-\vec r_2+\vec\rho_1(\phi_1)-\vec\rho_2(\phi_2)\rvert^2\right)$$

Where $\phi_i$ is a parameter describing the $i$-th square's perimeter, and

$$\vec\rho_i(\phi_i)=l\left[\frac{1-\Theta(\phi_i)}{\lvert\cos\phi_i\rvert}+\frac{\Theta(\phi_i)}{\lvert\sin\phi_i\rvert}\right]\left(\begin{array}{c} \cos(\phi_i+\theta_i)\\ \sin(\phi_i+\theta_i)\end{array}\right)\\ \Theta(\phi)=\left\{\begin{array}{cc} 0&&\left(0<\phi<\frac{\pi}{4}\right) \vee \left(\frac{3\pi}{4}<\phi<\frac{5\pi}{4}\right)\vee \left(\frac{7\pi}{4}<\phi<2\pi\right)\\1&&\left(\frac{\pi}{4}<\phi<\frac{3\pi}{4}\right) \vee \left(\frac{5\pi}{4}<\phi<\frac{7\pi}{4}\right)\end{array}\right.$$

Up to this point, I have the partial derivatives of $d^2$, but solving for the parameters has proven to be incredibly difficult, and even Mathematica is refusing to do it.

Any suggestion will be much appreciated.

• Possible solution: Use the given information about the squares to place them in the Cartesian plane, then use the fact that the closest point will always be one of the vertices of the two squares? (Unless two sides are parallel, but that case has infinitely many closest points) – Calconym Jul 26 '17 at 3:11
• Thank you. I know about what you're talking. But I was wondering if there is a way in which both squares are dealt with on equal footing, there is no post-selection process, and that handles by itself situations like the parallel sides. That's why I asked for a formula rather than an algorithm. – GeoArt Jul 26 '17 at 3:19
• You do treat the squares on equal footing with the vertex idea--the vertex you need could be on either square. And any algorithm can be made into a formula, but it is not always the case that there is any reasonable-looking formula that will do the same job as even a relatively simple algorithm. – David K Jul 26 '17 at 3:22
• I see; well given the usage of piecewise equations in your first attempt, would it be satisfactory to formulate the algorithm in a similar form? The algorithm is sufficiently simple to do that... but an algorithm on tasks like this will often have better performance than a formula. – Calconym Jul 26 '17 at 3:25
• OK, you're right. The post-selection is just a discrete version of the minimization after all. So, the suggestion would be to try the vertices from one square, perform the minimization on each interval of the piecewise function on the other square, flip the roles, and select the minimum from the 32 possibilities? – GeoArt Jul 26 '17 at 3:30