Created
December 6, 2018 21:12
-
-
Save sergeyprokudin/2d77e7f1ff441c2b47ff4d1fe440283c to your computer and use it in GitHub Desktop.
Sample uniformly from d-dimensional ball
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sample_dball_uniform(n_points=1000, n_dims=3): | |
"""Sample uniformly from d-dimensional ball | |
The code is inspired by this small note: | |
https://blogs.sas.com/content/iml/2016/04/06/generate-points-uniformly-in-ball.html | |
https://www.sciencedirect.com/science/article/pii/S0047259X10001211 | |
Parameters | |
---------- | |
n_points : int | |
number of samples | |
n_dims : int | |
number of dimensions | |
Returns | |
------- | |
x : numpy array | |
points sampled from d-ball | |
""" | |
n_points = 10000 | |
#sample point from d-sphere | |
x = np.random.normal(size=[n_points, n_dims]) | |
x_norms = np.sqrt(np.sum(np.square(x), axis=1)).reshape([-1, 1]) | |
x_unit = x / x_norms | |
#now sample radiuses uniformly | |
r = np.random.uniform(size=[n_points, 1]) | |
u = np.power(r, 1.0/n_dims) | |
x = x_unit*u | |
return x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment