Add deterministic LCG.

This commit is contained in:
Mike Bostock 2020-08-12 14:57:16 -07:00 committed by Philippe Rivière
parent 92b8ce3a09
commit 1e3db41373
3 changed files with 12 additions and 2 deletions

View File

@ -130,7 +130,7 @@ Returns the node closest to the position ⟨*x*,*y*⟩ with the given search *ra
<a name="simulation_randomSource" href="#simulation_randomSource">#</a> <i>simulation</i>.<b>randomSource</b>([<i>source</i>]) [<>](https://github.com/d3/d3-force/blob/master/src/simulation.js "Source"))
If *source* is specified, sets the function used to generate random numbers; this should be a function that returns a number between 0 (inclusive) and 1 (exclusive). If *source* is not specified, returns this simulations current random source which defaults to Math.random. A custom random source can be used to guarantee deterministic behavior. See also [*random*.source](https://github.com/d3/d3-random/blob/master/README.md#random_source).
If *source* is specified, sets the function used to generate random numbers; this should be a function that returns a number between 0 (inclusive) and 1 (exclusive). If *source* is not specified, returns this simulations current random source which defaults to a fixed-seed [linear congruential generator](https://en.wikipedia.org/wiki/Linear_congruential_generator). See also [*random*.source](https://github.com/d3/d3-random/blob/master/README.md#random_source).
<a name="simulation_on" href="#simulation_on">#</a> <i>simulation</i>.<b>on</b>(<i>typenames</i>, [<i>listener</i>]) [<>](https://github.com/d3/d3-force/blob/master/src/simulation.js#L145 "Source")

9
src/lcg.js Normal file
View File

@ -0,0 +1,9 @@
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
const a = 1664525;
const c = 1013904223;
const m = 4294967296; // 2^32
export default function() {
let s = 1;
return () => (s = (a * s + c) % m) / m;
}

View File

@ -1,5 +1,6 @@
import {dispatch} from "d3-dispatch";
import {timer} from "d3-timer";
import lcg from "./lcg.js";
export function x(d) {
return d.x;
@ -22,7 +23,7 @@ export default function(nodes) {
forces = new Map(),
stepper = timer(step),
event = dispatch("tick", "end"),
random = Math.random;
random = lcg();
if (nodes == null) nodes = [];