Generate a random point within a circle (uniformly)

前端 未结 21 2744
逝去的感伤
逝去的感伤 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:35

    Such a fun problem.
    The rationale of the probability of a point being chosen lowering as distance from the axis origin increases is explained multiple times above. We account for that by taking the root of U[0,1]. Here's a general solution for a positive r in Python 3.

    import numpy
    import math
    import matplotlib.pyplot as plt
    
    def sq_point_in_circle(r):
        """
        Generate a random point in an r radius circle 
        centered around the start of the axis
        """
    
        t = 2*math.pi*numpy.random.uniform()
        R = (numpy.random.uniform(0,1) ** 0.5) * r
    
        return(R*math.cos(t), R*math.sin(t))
    
    R = 200 # Radius
    N = 1000 # Samples
    
    points = numpy.array([sq_point_in_circle(R) for i in range(N)])
    plt.scatter(points[:, 0], points[:,1])
    

提交回复
热议问题