randomSample method

Quantity randomSample()

Randomly generates a Quantity from this Quantity's value and uncertainty. The uncertainty is represented by a Normal (Gaussian) continuous distribution.

Because the uncertainty is represented by the continuous normal distribution there are no upper or lower limits on the value that this method will return.

If the relative uncertainty is zero, then this Quantity will be returned.

Implementation

Quantity randomSample() {
  if (_ur == 0.0) return this;

  // Generate a random number btw 0.0 and 1.0
  final rand = math.Random().nextDouble();

  final test = 2.0 * rand - 1.0;

  // Iterate on erf until we get a close enough match
  var delta = 1.0;
  const eps = 0.0001;
  var x = -4.0;
  var count = 0;
  while (count < 10000) {
    final fx = erf(x);
    if ((fx - test).abs() < eps) {
      final z = x * math.sqrt(2.0);
      return this + (standardUncertainty * z);
    }

    // Reverse direction and halve it if past it
    if (fx > test) {
      x -= delta; // backtrack... went too far
      delta *= 0.5; // take smaller steps
    } else {
      x += delta;
    }

    count++; // safety valve
  }

  // just in case
  return this;
}