Position a rectangle inside a circle along the circumference

circlestrigonometry

Suppose I'd like to position a rectangle inside a circle such that:

  1. The center point of the rectangle (p, q) lies along the radius defined by θ
  2. The rectangle is positioned at the maximum radius from the circle center (without exiting the circle)

How can I determine the position (p, q) of the center of this rectangle (relative to the center of the circle (x, y))?

I have these parameters available:

  • r: radius of the circle
  • θ: angle of this radius along which (p,q) lies
  • w,h: width and height of the rectangle
  • x,y: location of the center of the circle

This question is related to the one asked by Mahozad, except they asked about the rectangle along the outside of the circle. In this question, I'm interested in the rectangle remaining inside the circle.

Images show $\theta \in (\pi/2, \pi)$ and $\theta=\pi,$ respectively.

Best Answer

Let $p^2 + q^2 = d^2$ where $d = f(\theta)$ represents distance of center of rectangle from center of circle as function of $\theta$.

Then $(p,q) = (x + d\cos\theta, y + d\sin\theta)$

Applying cosine law on triangle connecting center of circle, center of rectangle and vertex of rectangle touching the circle, $ d^2 + d (w \cos\theta + h \sin \theta) + {(\frac{w}{2})^2} + {(\frac{h}{2})^2} - r^2 = 0$

Solving quadratic equation for positive $d$, we get $d = \frac{\sqrt{(w \cos\theta + h \sin \theta)^2 + 4r^2 - w^2 - h^2}-(w \cos\theta + h \sin \theta)}{2}$

The above formula is valid for $\theta \in (0, \frac{\pi}{2})$. By symmetry, formula for other cases can be derived.

Let $m = \lfloor\frac{2\theta}{\pi} \rfloor$ and $\alpha = (-1)^m (\theta - \lfloor\frac{m+1}{2} \rfloor \pi)$

Then,for all angles, $d = \frac{\sqrt{(w \cos\alpha + h \sin \alpha)^2 + 4r^2 - w^2 - h^2}-(w \cos\alpha + h \sin \alpha)}{2}$

I wrote following code (with center of circle at (0,0)) demonstrating this formula in action.

import numpy as np

import matplotlib.pyplot as plt 
from matplotlib.patches import Rectangle

def c(r,w,h,theta):
    f = 2*theta // np.pi 
    th = (-1)**f * (theta - (f+1)//2 * np.pi)
    b = w*np.cos(th) + h*np.sin(th)
    d = ((b*b + 4*r*r - w*w - h*h)**0.5 - b)/2
    return (d*np.cos(theta), d*np.sin(theta))

theta = np.linspace(-np.pi,np.pi,100)
r = 10
w = 3 
h = 4 
center = np.array([c(r,w,h,t) for t in theta])
circle = np.array([[r*np.cos(t), r*np.sin(t)] for t in theta])

for cc in center:
    plt.gca().add_patch(Rectangle((cc[0]-w/2, cc[1]-h/2), w, h, fill=False))

plt.plot(center[:,0],center[:,1],'r')
plt.plot(circle[:,0], circle[:,1],'g')
plt.axis('square')
plt.show()

Red curve is the locus of center of rectangle.