Search code examples
javascriptmathgeometry2dpolar-coordinates

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


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)


Solution

  • 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;