sample method

Array sample(
  1. int n, {
  2. Random? random,
})

n random samples of the distribution (Box-Muller transform). Pass a seeded random for reproducible samples.

Implementation

Array sample(int n, {math.Random? random}) {
  if (n < 0) {
    throw FormatException('n must be >= 0, got $n');
  }
  random ??= math.Random();
  var samples = Array.fixed(n);
  for (var i = 0; i < n; i += 2) {
    // 1 - nextDouble() is in (0, 1], so the log is finite
    var u1 = 1.0 - random.nextDouble();
    var u2 = random.nextDouble();
    var r = math.sqrt(-2.0 * math.log(u1));
    samples[i] = mean + std * r * math.cos(2.0 * math.pi * u2);
    if (i + 1 < n) {
      samples[i + 1] = mean + std * r * math.sin(2.0 * math.pi * u2);
    }
  }
  return samples;
}