5

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?

cameronroytaylor
  • 1,578
  • 1
  • 17
  • 18
user77005
  • 1,769
  • 4
  • 18
  • 26

2 Answers2

14

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

Elisha
  • 23,310
  • 6
  • 60
  • 75
1

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)