mardi 1 décembre 2020

How to correctly generate a random unit vector in 3 dimensions?

I have already read this and this and the proposed solution is to pick each dimension from a gaussian distribution (why not uniform or any other ?) and then normalize. I do not really get that.

Also, I show my way and please let me know if it's right or wrong and why. Code is written in javascript.

const randBetween = (min, max) => {
  return Math.random() * (max - min) + min;
}

const shuffleArray = (array) => {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

const randomUnitVector = () => {
    const i = randBetween(-1, 1);
    const j = randBetween(-Math.sqrt(1 - i*i), Math.sqrt(1 - i*i));
    const k_ =  Math.sqrt(1 - i*i - j*j);
    const k = randBetween(-1, 1) < 0 ? -k_ : k_;
    return shuffleArray([i, j, k]);
}




Aucun commentaire:

Enregistrer un commentaire