Skip to content

Commit 52c3fda

Browse files
committed
Allow integer seeds.
1 parent 101b3a4 commit 52c3fda

File tree

2 files changed

+3
-4
lines changed

2 files changed

+3
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,4 @@ random(); // -0.6253955998897069
117117

118118
<a name="randomLcg" href="#randomLcg">#</a> d3.<b>randomLcg</b>([<i>seed</i>]) · [Source](https://github.com/d3/d3-random/blob/master/src/lcg.js), [Examples](https://observablehq.com/@d3/d3-randomlcg)
119119

120-
Returns a [linear congruential generator](https://en.wikipedia.org/wiki/Linear_congruential_generator); this function can be called repeatedly to obtain pseudorandom values well-distributed on the interval [0,1) and with a long period (up to 1 billion numbers), similar to Math.random. A *seed* can be specified as a number in the interval [0,1). Two generators instanced with the same seed generate the same sequence, allowing to create reproducible pseudo-random experiments. If the *seed* is not specified, one is chosen using Math.random.
120+
Returns a [linear congruential generator](https://en.wikipedia.org/wiki/Linear_congruential_generator); this function can be called repeatedly to obtain pseudorandom values well-distributed on the interval [0,1) and with a long period (up to 1 billion numbers), similar to Math.random. A *seed* can be specified as a real number in the interval [0,1) or as any integer. In the latter case, only the lower 32 bits are considered. Two generators instanced with the same seed generate the same sequence, allowing to create reproducible pseudo-random experiments. If the *seed* is not specified, one is chosen using Math.random.

src/lcg.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
22
const mul = 0x19660D;
33
const inc = 0x3C6EF35F;
4-
const eps = 1/0x100000000;
4+
const eps = 1 / 0x100000000;
55

66
export default function lcg(seed = Math.random()) {
7-
if (!(0 <= seed && seed < 1)) throw new RangeError("invalid seed");
8-
let state = seed / eps | 0;
7+
let state = (0 <= seed && seed < 1 ? seed / eps : Math.abs(seed)) | 0;
98
return () => (state = mul * state + inc | 0, eps * (state >>> 0));
109
}

0 commit comments

Comments
 (0)