开发者

When drawing a square inside a circle, can you assume the width of the square is 4/3 of the circle radius? [closed]

Closed. This question is off-topic. It is not currently accepting answers.

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 11 years ago.

Improve this question

I want to draw a square inside a circle. My circle has a radius of between 0.5 and 3.

is it safe to assume my square will always be 0.66 * 2 * radius wide/high?

I am making a function to calculate if a certain point is within the circle. I already made a square to get my points 开发者_StackOverflow中文版out of the database. I want to make the square within the circle to quickly determine if a point is definately within my circle


The length of the diagonal of the square corresponds to two times the radius of the circle, i.e.

d = 2 * r

At the same time it is

d = sqrt(2) * a

where a is the length of one side of your square.

Thus

a = r * 2 / sqrt(2) = r * sqrt(2)

which is approximately

a = r * 1.41421


A square that fits exactly in a circle should have a side length of sqrt(2) * radius.


This depends on what your definition of exactly is.

If you're using integer math, of course not because you can't represent it that course.

If you're using floating point arithmetic, then you can't because you could have rounding errors.

If you're using floating point arithmetic with a sufficiently course episilon, then assuming you've done your math right, yes you can make that assumption.

If you're using a decimal system that isn't floating point, then again assuming you've done your math right, yes you can make that assumption.


But regardless, if you want to determine if a point is within your circle, just use the Pythagorean theorem to get your distance to the center and compare the distance. You don't even have to use expensive square roots if you instead square the radius.

boolean isInCircle(Circle c, Point p) {

    double dx = c.center.x - p.x;
    double dy = c.center.y - p.y;
    double r2 = c.radius * c.radius;

    return dx*dx + dy*dy < r2;

}


Technically, yes, a square of 4/3*r will be entirely inside the circle, but that's not the biggest square inside the circle. An inscribed square has sides of sqrt(2)*r.

Regardless, the easiest way to calculate whether the point is inside the circle is to check if the point is less than radius away from the center; see glowcoder's code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜