random function

List<double> random(
  1. List<double> out,
  2. double? scale
)

Generates a random vector with the given scale

@param {vec4} out the receiving vector @param {Number} scale Length of the resulting vector. If omitted, a unit vector will be returned @returns {vec4} out

Implementation

List<double> random(List<double> out, double? scale) {
  scale ??= 1.0;

  // Marsaglia, George. Choosing a Point from the Surface of a
  // Sphere. Ann. math. Statist. 43 (1972), no. 2, 645--646.
  // http://projecteuclid.org/euclid.aoms/1177692644;
  double v1, v2, v3, v4;
  double s1, s2;
  do {
    v1 = GlMatrix.random() * 2 - 1;
    v2 = GlMatrix.random() * 2 - 1;
    s1 = v1 * v1 + v2 * v2;
  } while (s1 >= 1);
  do {
    v3 = GlMatrix.random() * 2 - 1;
    v4 = GlMatrix.random() * 2 - 1;
    s2 = v3 * v3 + v4 * v4;
  } while (s2 >= 1);

  double d = math.sqrt((1 - s1) / s2);
  out[0] = scale * v1;
  out[1] = scale * v2;
  out[2] = scale * v3 * d;
  out[3] = scale * v4 * d;
  return out;
}