How to create a random point inside a square, but NOT inside a circle cut inside a square

Reference Image:

The red circle has a radius r

The blue square has side length s

The goal is to create a random point in the blue zone, but not in the red zone. I already have a solution, but it includes trial and error, and this is not my preferred method, is there any mathematical solution to this problem?

Here is my method

Let rx and ry be random variables

rx = random number between 0 and s
ry = random number between 0 and s
while (distance(rx,ry,0,0) < r)
{
   rx = random number between 0 and s
   ry = random number between 0 and s
}
return rx ry;
Run codeHide result
+4
source share
6 answers

I will not enter into the discussion of mathematics or programming. For me, this question has both. This is my business.

, [0,1], . , . , , .

, :

  • , (x,y) (0,0).
  • a [0,1].
  • w = 2 * pi * a. . y = x * tan(w) , .
  • : , (rho) . r , , , 3, .
  • : . "" , w pi/4 3pi/4; " " w 3pi/4 5pi/4; " " w 5pi/4 7pi/4; "" w 7pi/4 2pi 0 pi/4.
  • : y = s / 2. , 3 , s/2 = xi tan(w).
  • (xi, s/2) rho: R = sqrt(xi^2 + (s/2)^2)
  • b [0,1]
  • [r, R]: rho = r + b * R
  • , X = rho * cos(w) Y = rho * sin(w), .

, 5 , , ( w).

, , , . , . , , . , ( , , ).

+2

, , .

- .

"" , / , , . (, , , .)


, (distance(rx,ry,0,0) - , , + *, , exp(x,2). , x*x + y*y < r2 if ( r2 = r*r; -).

+6

. , , . , , . , , . . (r, theta) , . , .

+3

However, as Marx stated, technically it is mathematics, not programming. However, the answer is to create a random point and determine if the length of the line drawn from the center of the square to that point is less than or equal to the radius of the circle. If so, reject it and create another.

0
source

You can generate two numbers in the range [0..1], and then define a function that maps x for some y to a point outside the circle.

0
source

Well, why reject both rx and ry if they are not the same? Any rx in [-s, s] may be our choice. Therefore;

rx = -s + 2*s*rand();

if(rx<-R || rx>R) % if rx is outside the critical area, you are free on ry
    ry = -s + 2*s*rand();
else % if rx is critical, we are restricted about choosing ry not within [-sqrt(R^2-rx^2),sqrt(R^2-rx^2)]
{
    rand_inst = rand();
    if(rand_inst<0.5) % for the first possible interval [-s, -sqrt(R^2-rx^2)]
        ry = -s + 2*(s-sqrt(R^2-rx^2))*rand_inst;
    else % for the second possible interval [sqrt(R^2-rx^2), s]
        ry = (sqrt(R^2-rx^2) - (s-sqrt(R^2-rx^2)) ) + 2*(s-sqrt(R^2-rx^2))*rand_inst;
}
0
source

All Articles