Pages

Friday, February 27, 2015

Generating a random point inside a circle


I assume, there is a circle of radius r = 1, on origin (0,0). And there is a point on the circle as (x,y)

Sine theta = y/r  ==> x (distance of point from origin on x-axis) = r * Cos theta

Cos theta = x/r   ==> y (distance of point from origin on y-axix) = y * Sin theta

Now, to generate any point within the circle, we can use above two equations. We need to generate two numbers: one for r and second for theta. The number for r should be between 0 and r so that its not away from the origin more than r. We can generate a random number between 0 and r. It would control the distance. Second parameter is Theta. Theta controls where this point should lie from between 0 and 2*Pi (360 degree). So, we need to generate a random number between 0 and 1 and multiply it with 2* Pi. This would give us angle value between 0 and 2* Pi (360 degree).

Thus,

r        =  random * 1; // it's pseudo code
Theta = 2 * Pi * (random*1); // theta

x =  r * Cos Theta
y =  r * Sine Theta.