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?
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:
And with the square root:
Sampling the angle and length like above doesn't guarantee uniform sampling from the circle. In this case, P(a) > P(b) if ||a|| > ||b||. In order to sample uniformly from a circle do the following :
length = np.random.uniform(0, 1)
angle = np.pi * np.random.uniform(0, 2)
x = np.sqrt(length) * np.cos(angle)
y = np.sqrt(length) * np.sin(angle)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With