aimless.js icon indicating copy to clipboard operation
aimless.js copied to clipboard

randIntRange non-uniform distribution

Open ChrisCavs opened this issue 1 year ago • 0 comments

Based on comments from HN and Reddit:

  • Math.floor(engine() * (max - min + 1)) + min creates bias, since the engine output bits do not divide evenly into the range
  • replace with rejection sampling

from vore on HN:

  function randBelow(n) {
    const nbits = Math.ceil(Math.log2(n));
    while (true) {
       const x = getRandBits(nbits);
       if (x < n) { return x; }
    }
  }

  function randIntHalfOpenRange(min, max) {
    return min + randBelow(max - min);
  }

  function randIntRange(min, max) {
    return randIntHalfOpenRange(min, max + 1);
  }

ChrisCavs avatar May 23 '23 15:05 ChrisCavs