diff --git a/src/distribution/internals/UnsafeUniformIntDistributionInternal.ts b/src/distribution/internals/UnsafeUniformIntDistributionInternal.ts index c4c3bd1a..da8aa807 100644 --- a/src/distribution/internals/UnsafeUniformIntDistributionInternal.ts +++ b/src/distribution/internals/UnsafeUniformIntDistributionInternal.ts @@ -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; }