Skip to content

Commit

Permalink
⚡️ Faster uniform distribution on small ranges (#516)
Browse files Browse the repository at this point in the history
  • Loading branch information
dubzzz committed Jan 9, 2023
1 parent a7e19a8 commit 464960a
Showing 1 changed file with 4 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@ import { RandomGenerator } from '../../generator/RandomGenerator';
* @internal
*/
export function unsafeUniformIntDistributionInternal(rangeSize: number, rng: RandomGenerator): number {
const MinRng = -0x80000000;
const NumValues = 0x100000000;

// Range provided by the RandomGenerator is large enough,
// given rangeSize <= 0x100000000 and RandomGenerator is uniform on 0x100000000 values
const MaxAllowed = NumValues - (NumValues % rangeSize);
let deltaV = rng.unsafeNext() - MinRng;
const MaxAllowed = rangeSize > 2 ? ~~(0x100000000 / rangeSize) * rangeSize : 0x100000000;
let deltaV = rng.unsafeNext() + 0x80000000;
while (deltaV >= MaxAllowed) {
deltaV = rng.unsafeNext() - MinRng;
deltaV = rng.unsafeNext() + 0x80000000;
}
return deltaV % rangeSize; // Warning: we expect NumValues <= 2**32, so diff too
return deltaV % rangeSize;
}

0 comments on commit 464960a

Please sign in to comment.