Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/int.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
}

Expand Down
35 changes: 35 additions & 0 deletions test/int-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Loading