Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
user77005 Avatar asked Dec 07 '22 16:12

user77005


2 Answers

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

like image 191
Elisha Avatar answered Dec 10 '22 04:12

Elisha


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)
like image 29
Chitwan Saharia Avatar answered Dec 10 '22 04:12

Chitwan Saharia