# Find maximum width of a rectangle contained with another (diagonally)

It appears that the question of figuring out if a rectangle will fit inside of another, specifically at a diagonal, has been asked before. As such, utilizing the equation linked here, I was able to determine if a rectangle will fit inside of another, regardless of its angle.

However, when considering the following diagram, I am struggling to re-purpose the equation to calculate the length of side P when sides A, B, and Q are known.

It's been a few years since I've dived into algebra, but I've spent a few days trying to figure this out (where was Wolfram Alpha when I was in high school?!?).

The ultimate result would be the ability calculate angle X (see diagram) given lengths Q, A, and B.

Am I on the right track in trying to use the equation linked above? Could I be approaching this problem in a more efficient manner? I'd really appreciate any guidance anyone can provide. Thank you in advance!

You can go directly for the angle $\alpha$ between sides $b$ and $q$ by requiring that the vectors for sides $p$ and $q$ are orthogonal, so their scalar product vanishes:

$\vec q = \left( \begin{array}{c} q \sin\alpha\\ q \cos\alpha \end{array} \right), \ \vec p = \left( \begin{array}{c} a - q \sin\alpha\\ q \cos\alpha - b \end{array} \right),$

$\vec p \cdot \vec q = (a - q \sin\alpha)\, q \sin\alpha + (q \cos\alpha - b)\, q \cos\alpha = 0 .$

For $\alpha \in [0,\pi/2]$ this is equivalent to

$a \sin\alpha - b\sqrt{1-\sin^2\alpha} + q(1-2\sin^2\alpha) = 0.$

This leads to an equation of degree 4 in $\sin\alpha$. This can be solved algebraically - but it is very cumbersome. (Try solve(ax - b\sqrt{1-x^2} + (1-2x^2)q=0,x) on WolframAlpha.)

For computation a numerical solution is easier to implement. Let us define

$g(x) = ax - b\sqrt{1-x^2} + q(1-2x^2),\\ f(\alpha) = g(\sin\alpha) = a \sin\alpha - b\sqrt{1-\sin^2\alpha} + q(1-2\sin^2\alpha).$

Now we have

$f(0) = g(0) = q-b < 0,\\ f(\pi/2) = g(1) = a-q > 0,$

so $g$ has (at least) one real root in $[0,1]$ and $f$ has (a) corresponding root(s) in $[0,\pi/2]$. Such a root can be found using bisection or Newton's method.