sampleTriangularPdf function

List<num> sampleTriangularPdf(
  1. int n,
  2. num min,
  3. num max,
  4. {int seed}
)

Returns a random sample following a symmetric triangular distribution with non-zero support over the range (min, max).

Throws an error of type ErrorOfType<InvalidFunctionParameter> if min >= max.

Implementation

List<num> sampleTriangularPdf(int n, num min, num max, {int? seed}) {
  if (min >= max) {
    throw ErrorOfType<InvalidFunctionParameter>(
      invalidState: 'min: $min >= max: $max',
      expectedState: 'min < max',
    );
  }

  num invCDF(num p, num min, num max) {
    final range = max - min;
    if (p < 0.5) {
      return min + range * sqrt(p / 2);
    } else {
      return max - range * sqrt((1.0 - p) / 2);
    }
  }

  final random = Random(seed);
  return List<num>.generate(n, (_) => invCDF(random.nextDouble(), min, max));
}