Tensor.randn constructor

Tensor.randn(
  1. List<int> shape, {
  2. double mean = 0.0,
  3. double std = 1.0,
  4. int? seed,
})

Creates a tensor with random values from a normal distribution.

Uses Box-Muller transform to generate N(0, 1) samples, then scales by std and shifts by mean.

Implementation

factory Tensor.randn(List<int> shape,
    {double mean = 0.0, double std = 1.0, int? seed}) {
  final size = _productOfShape(shape);
  final data = Float32List(size);
  final rng = seed != null ? math.Random(seed) : math.Random();
  // Box-Muller transform: pairs of uniform → normal
  for (int i = 0; i < size - 1; i += 2) {
    final u1 = rng.nextDouble();
    final u2 = rng.nextDouble();
    final r = math.sqrt(-2.0 * math.log(u1 == 0 ? 1e-10 : u1));
    final theta = 2.0 * math.pi * u2;
    data[i] = (r * math.cos(theta) * std + mean).toDouble();
    data[i + 1] = (r * math.sin(theta) * std + mean).toDouble();
  }
  // Handle odd size
  if (size.isOdd) {
    final u1 = rng.nextDouble();
    final u2 = rng.nextDouble();
    final r = math.sqrt(-2.0 * math.log(u1 == 0 ? 1e-10 : u1));
    data[size - 1] =
        (r * math.cos(2.0 * math.pi * u2) * std + mean).toDouble();
  }
  return Tensor(data, List<int>.from(shape));
}