randomNormalSource function

num Function() Function([num, num]) randomNormalSource(
  1. num source()
)

Returns a randomNormal function but where the given random number generator source is used as the source of randomness instead of Random.nextDouble.

The given random number generator must implement the same interface as Random.nextDouble and only return values in the range [0, 1). This is useful when a seeded random number generator is preferable to Random.nextDouble.

final seed = …; // any number in [0, 1)
final random = randomNormalSource(randomLcg(seed))(…);

Implementation

num Function() Function([num, num]) randomNormalSource(num Function() source) {
  return ([num mu = 0, num sigma = 1]) {
    num? x, r;
    return () {
      num y;

      // If available, use the second previously-generated uniform random.
      if (x != null) {
        y = x!;
        x = null;
      }

      // Otherwise, generate a new x and y.
      else {
        do {
          x = source() * 2 - 1;
          y = source() * 2 - 1;
          r = x! * x! + y * y;
        } while ((r == 0) || r! > 1);
      }

      return mu + sigma * y * sqrt(-2 * log(r!) / r!);
    };
  };
}