Search code examples
algorithmmathgeometryformulamathematical-optimization

Formula, Circle's perimeter intersects with corners of rectangle


enter image description here

Note: Everything about the circle is unknown. Only the width and height of the rectangle are known.

I devised a formula to determine the diameter of circle, so that the circle's perimeter intersects with the bottom two corners of a rectangle, whatever the proportion of the rectangle is (or at least if the width is greater than the height). The formula is as follows, whereby W refers to the width and H refers to the height of the rectangle:

X = W / H
Diameter = ((X/4) + (1/X)) * W

Does anybody know a more eloquent way to calculate this or is there a known algorithm to do this more efficiently?


Solution

  • Letting the center of the circle be (0, 0), the diameter be D, the width of the rectangle be W, and the height be H, the points (±W/2, D/2 − H) should lie on the circle, which by Pythagoras holds if and only if

    (W/2)2 + (D/2 − H)2 = (D/2)2.

    Expanding the binomial and subtracting (D/2)2 from both sides, we get

    W2/4 − D H + H2 = 0.

    Solving for D by adding D H to both sides and dividing through by H, we get

    D = W2/(4 H) + H.

    In code this could be as follows.

    double diameter(double width, double height) {
      return width * width / (4 * height) + height;
    }