Generate a random point within a circle (uniformly)

前端 未结 21 2924
逝去的感伤
逝去的感伤 2020-11-22 15:45

I need to generate a uniformly random point within a circle of radius R.

I realize that by just picking a uniformly random angle in the interval [0 ... 2π),

21条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 16:28

    1) Choose a random X between -1 and 1.

    var X:Number = Math.random() * 2 - 1;
    

    2) Using the circle formula, calculate the maximum and minimum values of Y given that X and a radius of 1:

    var YMin:Number = -Math.sqrt(1 - X * X);
    var YMax:Number = Math.sqrt(1 - X * X);
    

    3) Choose a random Y between those extremes:

    var Y:Number = Math.random() * (YMax - YMin) + YMin;
    

    4) Incorporate your location and radius values in the final value:

    var finalX:Number = X * radius + pos.x;
    var finalY:Number = Y * radois + pos.y;
    

提交回复
热议问题