sample method

  1. @override
T sample({
  1. Random? random,
})
override

Generates a random sample.

Example

import 'package:calc/calc.dart';

void main() {
  final distribution = NormalDistribution(mean=0.0, variance:1.0);
  final sample = distribution.sample();
}

Implementation

@override
T sample({Random? random}) {
  final masses = _masses;
  if (masses.isEmpty) {
    throw StateError('Frequencies is empty');
  }
  random ??= Random();

  // Choose a random threshold
  final x = random.nextDouble();

  // Iterate until the sum exceeds threshold
  var sum = 0.0;
  for (var entry in masses.entries) {
    sum += entry.value;
    if (sum > x) {
      return entry.key;
    }
  }

  // Fallback
  return masses.keys.first;
}