From ca0a54d4a628e130a7a7cbc6df5b1468d91497e7 Mon Sep 17 00:00:00 2001 From: Jacob Rus Date: Sat, 22 Aug 2020 02:44:07 -0700 Subject: [PATCH 1/3] speed up 10x (Safari) or 4x (Chrome/Firefox) --- src/lcg.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/lcg.js b/src/lcg.js index 4aa1b07..c466eb7 100644 --- a/src/lcg.js +++ b/src/lcg.js @@ -1,10 +1,13 @@ // https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use -const a = 1664525; -const c = 1013904223; -const m = 4294967296; // 2^32 +const mul = 0x19660D; +const inc = 0x3C6EF35F; +const lo32 = 0xFFFFFFFF; +const eps = Math.pow(2, -32); -export default function lcg(s = Math.random()) { - if (!(0 <= s && s < 1)) throw new RangeError("invalid seed"); - s = Math.floor(m * s); - return () => (s = (a * s + c) % m) / m; +export default function lcg(seed = Math.random()) { + if (!(0 <= seed && seed < 1)) throw new RangeError("invalid seed"); + let state = Math.floor((1+lo32) * seed); + return function random () { + return eps * ((state = (mul * state + inc) & lo32) >>> 0); + }; } From d6e3b15d1f048821372929a993f11bde2d43c7cf Mon Sep 17 00:00:00 2001 From: Jacob Rus Date: Sat, 22 Aug 2020 17:09:18 -0700 Subject: [PATCH 2/3] shorten code, slightly faster still --- src/lcg.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/lcg.js b/src/lcg.js index c466eb7..a31c7eb 100644 --- a/src/lcg.js +++ b/src/lcg.js @@ -1,13 +1,10 @@ // https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use const mul = 0x19660D; const inc = 0x3C6EF35F; -const lo32 = 0xFFFFFFFF; -const eps = Math.pow(2, -32); +const eps = 1/0x100000000; export default function lcg(seed = Math.random()) { if (!(0 <= seed && seed < 1)) throw new RangeError("invalid seed"); - let state = Math.floor((1+lo32) * seed); - return function random () { - return eps * ((state = (mul * state + inc) & lo32) >>> 0); - }; + let state = seed/eps | 0; + return () => (state = mul * state + inc | 0, eps * (state >>> 0)); } From f3ac45bf238bd58b9f9f691d8d9fed97bd697b3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Rivi=C3=A8re?= Date: Wed, 26 Aug 2020 20:08:42 +0200 Subject: [PATCH 3/3] Update src/lcg.js Co-authored-by: Mike Bostock --- src/lcg.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lcg.js b/src/lcg.js index a31c7eb..cbdfaf1 100644 --- a/src/lcg.js +++ b/src/lcg.js @@ -5,6 +5,6 @@ const eps = 1/0x100000000; export default function lcg(seed = Math.random()) { if (!(0 <= seed && seed < 1)) throw new RangeError("invalid seed"); - let state = seed/eps | 0; + let state = seed / eps | 0; return () => (state = mul * state + inc | 0, eps * (state >>> 0)); }