ENH: Support Random Unit Vector
See original GitHub issueIs your feature request related to a problem? Please describe.
Proposed new feature or change:
Description
Often you want to randomize a “direction” that doesn’t have “size”. This can be useful when:
- You want to randomize the direction of an NPC walk in a 2D or 3D games, where its speed is a predefined constant.
- You’re developing particles simulation with all particles moving in random directions
- etc.
This random direction should be an n
th dimensional unit vector which is randomized uniformly from the unit sphere. That means that sections of the unit sphere with equal areas should have the same chance of getting a vector from.
Implementation
If one wants to randomize n
th dimensional direction uniformly, one must do the following:
- Generate
n
components of the vector using the standard normal distribution - Find the norm the generated vector
- Divide the vector by its norm
In simple Python code:
import numpy as np
from scipy import stats
def sphere_uniform(n: int):
vec = stats.norm.rvs(size=n)
size = np.linalg.norm(vec)
return vec / size
This implementation suggestion is based on this blog post. I’m not sure if there’s a faster way of implementing it using C++ and Cython, but I’m confident that someone here will know.
Why Implement It in Scipy?
Originally, I suggested implementing it on Numpy (numpy/numpy#21523), but they stated that they are not interested in expending the numpy.random
library and suggested adding this new feature as part of scipy.stats
.
I believe that random unit vectors are common enough to be a part of Numpy or Scipy, which are two of the most popular python libraries (if not the most popular ones). Scientists, gamers and engineers use random directions all the time, and I believe there is no reason why this ability shouldn’t be provided out-of-the-box.
Issue Analytics
- State:
- Created a year ago
- Comments:16 (11 by maintainers)
The former, I think. It would fit well as a subclass of
multi_rv_generic
in_multivariate.py
.Uniformly-random vectors on the unit hypersphere is an important multivariate distribution. It’s not hard to implement oneself, if one knows the necessary trick (and yes, the normal distribution is necessary). If one doesn’t know the appropriate trick, ad hoc implementations tend to fail in ways that are hard to diagnose in higher dimensions than 2.