What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario:

  1. A rectangular area with dimensions length l and breadth b
  2. A circle with a radius r
  3. The circle is positioned inside the rectangular area as depicted in the image below

Check out the image here - Red areas show expected evenly distributed coordinates

How can we randomly generate coordinates outside the circle within the rectangular area that are also evenly distributed? (within the blue region shown in the image below)

Answer №1

Produce two random values within specified ranges (following a uniform distribution in a rectangle)

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

Determine if the point is situated outside the circle:

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

If not, repeat the random generation process until the condition is met (utilizing the rejection method)

https://i.sstatic.net/VUEb7.png

This Delphi code was used to generate the above:

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;

Answer №2

Begin by creating a random distribution of x and y values within a square, discarding any pairs falling outside the confines of a centered rectangle.

Procedure

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;
while true
  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;
  

Next, verify if x and y fall within the circular boundary.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for the emergence of this error message: "TypeError: mkdirp is not recognized as a function"?

While running the code, I encountered an error indicating that the file creation process was not working. I am seeking assistance to resolve this issue. The code is designed to fetch data from the Naver Trend API and Naver Advertising API, calculate resul ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...

How can MessagePorts be effectively utilized in electron Js?

What are some real-world applications of using MessagePorts in Electron JS? Why is it necessary instead of just using ipcRenderer.invoke? I haven't been able to identify any practical scenarios where MessagePorts are indispensable. It seems like it&ap ...

Styling is applied by Bootstrap to inputs in a form that are not required

I am currently working on validating a form for empty fields using Bootstrap. When submitting and validating the form with the form.checkValidity() method, I noticed that even the non-required fields are being styled as if they are required. Is this normal ...

When registering the onHardwareBackButton event in Ionic, the back button continues to successfully navigate to the previous page

I recently started working with Ionic and encountered an issue with the onHardwareBackButton event. The event is functioning properly and directing me to the register function, but even after going to the register function, it still navigates back to the p ...

Testing the mongoose.connect callback method in Jest: A step-by-step guide

Currently working on a new Express application and utilizing Jest as the testing framework. All sections of code have been successfully covered, except for the callback of the mongoose.connect method: I attempted to spy on the connect method of the mongo ...

Is it possible to use a hash map to monitor progress while looping through this array in JavaScript?

I've been exploring some algorithmic problems and I'm puzzled about the most efficient way to solve this particular question. While nested for loops are an option, they don't seem like the optimal choice. I'm considering using a hash ma ...

Flashing Effect of Angular Ui-Bootstrap Collapse During Page Initialization

Below is the code snippet I've implemented to use the ui-bootstrap collapse directive in my Angular application. HTML: <div ng-controller="frequencyCtrl" style="margin-top:10px"> <button class="btn btn-default" ng-click="isCollapsed = ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Developing a customizable datepicker with the ability to select specific months or date ranges

I am currently developing a WebApp using flask and constructing templates in HTML/JS for the front end. I am in need of a datepicker that will provide the user with the option to choose a specific date range or select a range of months. Take a look at the ...

Managing numerous JavaScript objects within a plugin

I have developed a straightforward javascript plugin that enables me to gather data from specific html elements. A page can contain x number of elements (usually up to 20), each with its own settings. However, the issue I am facing is that the returned obj ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

React component failing to update upon rerender

I've encountered an issue with my Flux setup where the component doesn't rerender when adding a new Todo, although it does when deleting or changing the checkbox. I find this behavior confusing and wonder what might be causing it. The list itself ...

Adding JQuery to a running webpage using the DOM and Opera browser add-ons

I'm currently working on an Opera Extension and I have a question. Is there a way to use the includes folder in order to directly inject jQuery into the live HTML of a webpage? For example, can I change the background color of the DOM to black? If ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

Automatically selecting the map center while using the Drawing Manager feature for placing markers

My application utilizes the Google Drawing Library. When a user clicks on the Add New Marker Button, the Drawing Manager is activated allowing the user to generate a marker by clicking anywhere on the map. Subsequently, the following listener is executed: ...

The fonts in node.js are not functioning as expected, without displaying any error messages

I'm having trouble implementing custom fonts on my website. Despite following the correct file structure, the fonts do not seem to be loading. My project files are organized in the following manner: https://gyazo.com/5ee766f030290e5b2fa42320cc39f10b ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

Create a duplicate <li> element and animate it using jQuery

Here are the list items: <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</l ...

Retrieve user information from Auth0 once the user has completed the signup process

I am looking to integrate the ability to create new users on Auth0 through my admin panel. Currently, I am utilizing Auth0 lock for signups, but now I need to store these users in my Database, which requires their email and Auth0 user ID. I am exploring o ...