Search code examples
pythonuniform-distribution

Sampling Uniformly within the Unit Circle


I want to sample a two-dimensional vector x from a uniform distribution with ∥x∥ ≤ 1. I know I can sample from a uniform distribution as

numpy.random.uniform(0.0, 1.0, 2)

but how can I make sure ∥x∥ ≤ 1?


Solution

  • It can be done by randomizing angle and length and convert them into cartesian coordinates:

    import numpy as np
    
    length = np.sqrt(np.random.uniform(0, 1))
    angle = np.pi * np.random.uniform(0, 2)
    
    x = length * np.cos(angle)
    y = length * np.sin(angle)
    

    Edit: iguarna comment about the original answer is correct. In order to draw a point uniformly, the length needs to be the square root of the random number drawn. A reference to it can be found here: Simulate a uniform distribution on a disc. To exemplify, this is the result of random results without the square root: Without square root And with the square root: With square root