Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
Adrin Avatar asked Dec 17 '25 19:12

Adrin


2 Answers

Due to Jacobian, you have to take square root

r = R *  Math.sqrt(Math.random());
like image 69
Severin Pappadeux Avatar answered Dec 19 '25 08:12

Severin Pappadeux


To evenly distribute points within the circle, just pick random points in a square with side-length equal to 2R, and then discard any point that falls outside of the circle.

This can be done without any trigonometric or transcendental operations:

let x, y;
do {
    x = 2 * Math.random() - 1.0;  // range [-1, +1)
    y = 2 * Math.random() - 1.0;
} while ((x * x + y * y) >= 1);   // check unit circle

// scale and translate the points
x = x * R + Mx;
y = y * R + My;

In each pass of the loop about 21.5% of points will be discarded but this should still end up faster than using sin and cos.

like image 28
Alnitak Avatar answered Dec 19 '25 09:12

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!