Skip to content

Commit 97c3c8a

Browse files
authored
Merge pull request #36 from jrus/patch-1
speed LCG up 10x (Safari) or 4x (Chrome/Firefox)
2 parents 637bce1 + f3ac45b commit 97c3c8a

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

src/lcg.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
2-
const a = 1664525;
3-
const c = 1013904223;
4-
const m = 4294967296; // 2^32
2+
const mul = 0x19660D;
3+
const inc = 0x3C6EF35F;
4+
const eps = 1/0x100000000;
55

6-
export default function lcg(s = Math.random()) {
7-
if (!(0 <= s && s < 1)) throw new RangeError("invalid seed");
8-
s = Math.floor(m * s);
9-
return () => (s = (a * s + c) % m) / m;
6+
export default function lcg(seed = Math.random()) {
7+
if (!(0 <= seed && seed < 1)) throw new RangeError("invalid seed");
8+
let state = seed / eps | 0;
9+
return () => (state = mul * state + inc | 0, eps * (state >>> 0));
1010
}

0 commit comments

Comments
 (0)