55

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.

Sracanis
  • 490
  • 5
  • 25
Mouseroot
  • 1,034
  • 2
  • 9
  • 13
  • 3
    this inst homework its more of im tired of googleing for only part of the equation and having to figure it out by trial and error. – Mouseroot Mar 26 '12 at 20:49

2 Answers2

122

Just get a random angle:

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

Then

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

Done.

Mehraban
  • 3,164
  • 4
  • 37
  • 60
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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

kunigami
  • 3,046
  • 4
  • 26
  • 42
  • 1
    Interesting solution. As an aside, note that efficiency through avoidance of trigonometric functions is likely a matter of architecture. Nearly all modern VLSI processors contain a Floating Point Unit (FPU) incorporating transcendental functions, making this algorithm very likely less performant as compared to the selected answer. On the other hand, if using a processor without a FPU (eg, the Arduino architecture) this algorithm might be more efficient than using libraries that compute Cos and Sin... Empirical testing of course will need to vet this... – Trentium Aug 21 '22 at 15:40