Search code examples
javascriptmathvectorvector-graphics

Generate random 5d vector of given magnitude


Given a five dimensional space, I would like to generate 100 vectors, all with a fixed magnitude=M, where the components values are randomly distributed.

I was originally thinking of starting off with a unit vector and then applying a rotation matrix, with random parameters for the 10 degrees of freedom ... Would this work? and how?

Any nice way of doing this in Javascript...?

cheers for any pointers!


Solution

  • Here is the Monte Carlo algorithm that I would use (I do not know Javascript well enough to code in it off the top of my head):

    1. Generate random values in the range from -1 to 1 for each of the five dimensions.

    2. Calculate the Magnitude M, if M=0 or M>1 then reject these values and return to step #1.

    3. Normalize the vector to have a Magnitude of 1 (divide each dimension by M).

    That should give you random unit vectors evenly distributed over the 5-dimensional super-sphere surface.


    The question has been asked: "Why reject the vector if M>1?"

    Answer: So that the final vectors will be uniformly distributed across the surface of the unit 5-sphere.

    Reasoning: What we are generating in the first step is a set of random vectors that are uniformly distributed within the volume of the unit 5-cube. Some of those vectors are also within the volume of the unit 5-sphere and some of them are outside of that volume. If normalized, the vectors within the 5-sphere are evenly distributed across its surface, however, the ones outside it are not at all evenly distributed.

    Think about it like this: Just as with a normal 3-dimensional Unit Cube and Unit Sphere, or even the Unit Square and the Unit Circle, the Unit 5-Sphere is wholly contained within the Unit 5-Cube, which touches only at the five positive unit dimension axis points:

    (1,0,0,0,0)
    (0,1,0,0,0)
    (0,0,1,0,0)
    (0,0,0,1,0)
    (0,0,0,0,1)
    

    and their corresponding negative unit axis points. This is because these are the only points on the surface of the cube that have a magnitude (distance from the origin) of 1, at all other points, the 5-cube's surface has a distance from the origin that is greater than 1.

    And this means that there are many more points between (0,0,0,0,0) and (1,1,1,1,1) than there are between (0,0,0,0,0) and (1,0,0,0,0). In fact about SQRT(5) or aprx. 2.25 times more.

    And that means that if you included all of the vectors in the unit 5-cube, you would end up with more than twice as many results "randomly" mapping to about (0.44,0.44,0.44,0.44,0.44) than to (1,0,0,0,0).


    For those who are challenging (without foundation, IMHO) that this results in a uniform distribution across the surface of the 5-D Sphere, please see the alternative method in this Wikipedia article section: https://en.wikipedia.org/wiki/N-sphere#Uniformly_at_random_on_the_(n_%E2%88%92_1)-sphere