views:

60

answers:

2

I have a rectangle, and a circle inside that rectangle (that sits around the center of the rectangle). I want to generate a random 2-component vector that falls inside the rectangle, but not the circle. How can I do it?

Edit: I'd prefer a method that i can use to generate a vector that meets these constraints without brute-forcing it.

A: 
Vector = Rectangle.RandomVector();

while (Circle.Contains(Vector)) {
    Vector = Rectangle.RandomVector();
}

Aka, just brute force it. It has a 21.5% chance of being outside the circle every time :)

Mike Caron
How did you calculate that 21.5%? There doesn't seem to be enough information from the OP to obtain such a statistic.
Wallacoloo
Not so! He describes a circle inscribed within a rectangle (and, I'm assuming a square based on that). The area of the circle is 78.5% of the area of the square. Thus, a 21.5% chance of it being within the square, but outside the circle. (If the circle is actually smaller than the rectangle, the percentage goes up, but the idea is the same)
Mike Caron
I never said the circle goes out to any of the edges of the circle; it's likely in fact that it won't.
RCIX
Okay. Even so, my answer is still valid. There's really no other practical way to go about it than churning positions until you get one that works.
Mike Caron
A: 

Generate random numbers for the x and y component of the vector such that x < rectangle.width and y < rectangle.heigth. Then check whether x^2 + y^2 < circle.radius^2 and throw the vector away if so.

Update: Another way which generates a non uniform distribution but doesn't throw away any vector is as follows: Randomly choose an angle from the interval 0 to 2*pi. Now determine the length of the vector by randomly choosing a value from the interval determined by the intersections of the line with the former angle starting at the center with the circle and the rectangle. The resulting distribution will be uniform when protected onto the circle. It will also be uniform for each angle. It wont be uniform in the plane however.

michid
I got that setup, but i'd rather not potentially throw away a bunch of vectors...
RCIX
Unfortunately, that's the only way to keep it uniformly distributed. :(
glowcoder
@Glowcoder: i might not mind a non uniform distribution, depending on what it is. Mind elaborating in an answer?
RCIX
You could keep some of the vectors by say... switching the x and y coords and seeing if that vector still lies in the circle. This would allow you to keep the total random numbers generated down.
glowcoder