Wolfram Research

Function Repository Resource:

RandomUnitVector

Source Notebook

Generate random vectors in any dimension of unit length

Contributed by: Sander Huisman  |  SHuisman

ResourceFunction["RandomUnitVector"][d]

generates a d-dimensional unit vector.

ResourceFunction["RandomUnitVector"][d,n]

generates n d-dimensional unit vectors.

ResourceFunction["RandomUnitVector"][d,{n1,n2,n3,}]

generates an n1n2n3 array of d-dimensional unit vectors.

Details

ResourceFunction["RandomUnitVector"][] generates a single two-dimensional unit vector.

Examples

Basic Examples (2) 

Generate a two-dimensional unit vector:

In[1]:=
ResourceFunction["RandomUnitVector"][2]
Out[1]=

Generate 5 random three-dimensional unit vectors:

In[2]:=
ResourceFunction["RandomUnitVector"][3, 5]
Out[2]=

Scope (3) 

Generate a 4×6 array of 3D unit vectors:

In[3]:=
ruvs = ResourceFunction["RandomUnitVector"][3, {4, 6}]
Out[3]=

Check the dimensions:

In[4]:=
Dimensions[ruvs]
Out[4]=

Check the magnitudes:

In[5]:=
Map[Norm, ruvs, {2}]
Out[5]=

Applications (2) 

Generate a random points on a circle:

In[6]:=
Graphics[ResourceFunction["RandomUnitVector"][2, 500] // Point, ImageSize -> 200]
Out[6]=

Generate some random points on a sphere and compare with built-in functionality:

In[7]:=
{
 Graphics3D[ResourceFunction["RandomUnitVector"][3, 1000] // Point, ImageSize -> 200],
 Graphics3D[RandomPoint[Sphere[], 1000] // Point, ImageSize -> 200]
 }
Out[7]=

Properties and Relations (1) 

Check the uniformity of the unit vectors:

In[8]:=
Histogram[
 ArcTan @@@ ResourceFunction["RandomUnitVector"][2, 100000], {-Pi, Pi,
   Pi/100}]
Out[8]=

Neat Examples (2) 

Perform a 2D random walk with steps of unit length:

In[9]:=
Graphics[Arrow[
  Accumulate[ResourceFunction["RandomUnitVector"][2, 100]]]]
Out[9]=

Perform a 3D random walk with steps of unit length:

In[10]:=
Graphics3D[
 Arrow[Tube[Accumulate[ResourceFunction["RandomUnitVector"][3, 100]], 0.1]]]
Out[10]=

Resource History

Source Metadata

Related Resources

License Information