How to generate random coordinates outside the circle contained in a rectangular region?

217 Views Asked by At

Given:

  1. Rectangular region with length l & breadth b
  2. Circle with radius r
  3. Circle is contained in rectangular region like shown in below image

See image here - Red are expecting evenly distributed coordinates

Then how to generate random coordinates outside the circle contained in a rectangular region and evenly distributed? (in blue region of below image)

2

There are 2 best solutions below

8
MBo On BEST ANSWER

Generate two random values in ranges (uniform distribution in rectangle)

a = Math.random() * width
b = Math.random() * height

check if point lies outside the circle:

(a-center_x)*(a-center_x)+(b-center_y)*(b-center_y) > r*r

if not - repeat random generation until condition becomes true (this is rejection method)

enter image description here

Generated by this Delphi code for reference

var
  Hgt, Wdt, i, N, CX, CY, R, x, y: Integer;
begin
  Hgt := 300;
  Wdt := 400;
  CX := 220;
  CY := 120;
  R := 100;
  N := 15000;
  for i := 0 to N-1 do begin
    x := Round(Random() * Wdt);
    y := Round(Random() * Hgt);
    while (x-CX)*(x-CX)+(y-CY)*(y-CY) < R*R do begin
      x := Round(Random() * Wdt);
      y := Round(Random() * Hgt);
    end;
    Canvas.Pixels[x, y] := clRed;
  end;
4
chux - Reinstate Monica On

First generate a uniform distribution of x, y values in a square and reject any x,y outside the centered rectangle.

Algorithm

max_dimension = max(l, b)
min_x = (max_dimension-l)/2;
max_x = min_x + l;
min_y = (max_dimension-b)/2;
max_y = min_y + b;
loop forever
  x = Math.random()*max_dimension
  if (x < min_x || x > max_x) continue;
  y = Math.random()*max_dimension
  if (y < min_y || x > max_y) continue;
  

Now test if x, y inside the circle

  xc = x - l/2;
  yc = y - b/2;
  if (xc*xc + yc*yc < r*r) continue
  break
}