Generate a random point within a circle (uniformly)

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

    Let ρ (radius) and φ (azimuth) be two random variables corresponding to polar coordinates of an arbitrary point inside the circle. If the points are uniformly distributed then what is the disribution function of ρ and φ?

    For any r: 0 < r < R the probability of radius coordinate ρ to be less then r is

    P[ρ < r] = P[point is within a circle of radius r] = S1 / S0 =(r/R)2

    Where S1 and S0 are the areas of circle of radius r and R respectively. So the CDF can be given as:

              0          if r<=0
      CDF =   (r/R)**2   if 0 < r <= R
              1          if r > R
    

    And PDF:

    PDF = d/dr(CDF) = 2 * (r/R**2) (0 < r <= R).
    

    Note that for R=1 random variable sqrt(X) where X is uniform on [0, 1) has this exact CDF (because P[sqrt(X) < y] = P[x < y**2] = y**2 for 0 < y <= 1).

    The distribution of φ is obviously uniform from 0 to 2*π. Now you can create random polar coordinates and convert them to Cartesian using trigonometric equations:

    x = ρ * cos(φ)
    y = ρ * sin(φ)
    

    Can't resist to post python code for R=1.

    from matplotlib import pyplot as plt
    import numpy as np
    
    rho = np.sqrt(np.random.uniform(0, 1, 5000))
    phi = np.random.uniform(0, 2*np.pi, 5000)
    
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    
    plt.scatter(x, y, s = 4)
    

    You will get

提交回复
热议问题