truncatedNormalPdf function

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

Truncated normal 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 truncatedNormalPdf(
  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',
    );
  }
  stdDev = stdDev.abs();
  if (x < min || x > max) {
    return 0.0;
  } else {
    final invStdDev = 1.0 / stdDev;
    return stdNormalPdf((x - mean) * invStdDev) /
        (stdNormalCdf((max - mean) / stdDev) -
            stdNormalCdf((min - mean) / stdDev)) *
        invStdDev;
  }
}