Mouseroot
Mouseroot

Reputation: 1064

How can I generate random points on a circles circumference in javascript

I am trying to write a function that will randomly return an (x,y) co-ordinates around a given circumference so if I have a point that's at (0,0) (being the center of the div) how can I write a function that randomly places other entities that appear among the outer edge of a circle.

All I need is the equation i know it has something to do with getting the distance from the center to the circumference edge just no idea how to calculate it and randomize it so it looks good.

Upvotes: 57

Views: 44428

Answers (2)

kunigami
kunigami

Reputation: 3086

You can also avoid computing sin and cos via this formula:

// Generate 2 random numbers in the [-1, 1] interval
const u = Math.random()*2 - 1;
const v = Math.random()*2 - 1;

const u2 = u*u;
const v2 = v*v;
const r = u2 + v2;

if (r <= 1) {
  x = (u2 - v2)/r;
  y = (2*u*v)/r;
}

if r > 1 you need to re-try, but the expected number of tries until you get a valid point is ~1.27. So this algorithm is very efficient and avoids the complex trigonometric functions.

Visualization: https://observablehq.com/@kunigami/circles-and-randomness

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Just get a random angle:

var angle = Math.random()*Math.PI*2;

Then

x = Math.cos(angle)*radius;
y = Math.sin(angle)*radius;

Done.

Upvotes: 124

Related Questions