Search code examples
javascriptmathrandompolar-coordinates

Random points all over inside of a circle


I'm using below code to randomly generate some x,y s that are located inside of a circle:

// r is distance from the center and a is angle
// R is radius of circle
// M is center

r = R * Math.random();
a = 2 * Math.PI * Math.random();

x = Math.round(r * Math.cos(a) + M);
y = Math.round(r * Math.sin(a) + M);

the problem is while moving closer and closer to the center of the circle, the chance to get x,y in that location gets more and more.

But What I'm looking for is just to have completely random x,y all over in the circle. How can I achieve this?


Solution

  • Due to Jacobian, you have to take square root

    r = R *  Math.sqrt(Math.random());