diff --git a/src/int.js b/src/int.js index a47249b..3e4eae5 100644 --- a/src/int.js +++ b/src/int.js @@ -6,7 +6,7 @@ export default (function sourceRandomInt(source) { min = Math.floor(min); max = Math.floor(max) - min; return function() { - return Math.floor(source() * max + min); + return Math.floor(source() * max) + min; }; } diff --git a/test/int-test.js b/test/int-test.js index 0fab540..3f87193 100644 --- a/test/int-test.js +++ b/test/int-test.js @@ -24,3 +24,38 @@ it("randomInt(min, max) returns random integers in the range [min, max - 1]", () const r = randomInt.source(randomLcg(0.9598431138570096)); assert.deepStrictEqual(extent(range(10000).map(r(10, 42))), [10, 41]); }); + +it("randomInt(min, max) excludes the upper bound for a negative interval", () => { + const r = randomInt.source(() => 1 - 2 ** -53); + assert.strictEqual(r(-3, -2)(), -3); +}); + +it("randomInt(min, max) excludes the upper bound for a positive interval", () => { + const r = randomInt.source(() => 1 - 2 ** -53); + assert.strictEqual(r(1, 2)(), 1); +}); + +it("randomInt(min, max) excludes the upper bound with a large offset", () => { + const min = 2 ** 52; + const r = randomInt.source(() => 1 - 2 ** -53); + assert.strictEqual(r(min, min + 2)(), min + 1); +}); + +it("randomInt(max) excludes the upper bound for a source near one", () => { + const r = randomInt.source(() => 1 - 2 ** -53); + assert.strictEqual(r(4)(), 3); +}); + +it("randomInt normalizes fractional bounds before sampling", () => { + const r0 = randomInt.source(() => 0); + const r1 = randomInt.source(() => 1 - 2 ** -53); + assert.strictEqual(r0(2.9, 5.9)(), 2); + assert.strictEqual(r1(2.9, 5.9)(), 4); + assert.strictEqual(r1(4.9)(), 3); +}); + +it("randomInt handles the legal source boundaries and a binary midpoint", () => { + assert.strictEqual(randomInt.source(() => 0)(-3, -2)(), -3); + assert.strictEqual(randomInt.source(() => 1 - 2 ** -53)(0, 1)(), 0); + assert.strictEqual(randomInt.source(() => 0.5)(-3, -1)(), -2); +});