truncatedNormalCdf function

num truncatedNormalCdf(
  1. num x,
  2. num min,
  3. num max,
  4. num mean,
  5. num stdDev
)

Truncated normal cumulative probability density function with parameters:

  • min: left limit.
  • max: right limit satisfying min < max.
  • mean: sample mean satisfying min < mean < max.
  • stdDev: corrected sample standard deviation. Must be a positive number.
  • truncatedNormalPdf(x) > 0 for x in the range (min, max) and zero elsewhere.

Throws an error of type ErrorOfType<InvalidFunctionParameter> if min >= max or if mean is outside the interval (min, max).

Implementation

num truncatedNormalCdf(
  num x,
  num min,
  num max,
  num mean,
  num stdDev,
) {
  if (min >= max) {
    throw ErrorOfType<InvalidFunctionParameter>(
      invalidState: 'min: $min >= max: $max',
      expectedState: 'min < max',
    );
  }
  if (mean < min || mean > max) {
    throw ErrorOfType<InvalidFunctionParameter>(
      message: 'Invalid parameter mean: $mean.',
      invalidState: 'min: $min < mean: $mean < max: $max',
    );
  }

  final invStdDev = 1.0 / stdDev;

  if (x <= min) return 0.0;
  if (x >= max) return 1.0;

  return (stdNormalCdf((x - mean) * invStdDev) -
              stdNormalCdf((min - mean) * invStdDev)) /
          (stdNormalCdf((max - mean) * invStdDev)) -
      stdNormalCdf((min - mean) * invStdDev);
}