Skip to content

Commit

Permalink
Add deterministic LCG.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock authored and Fil committed Aug 15, 2020
1 parent 92b8ce3 commit 1e3db41
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 simulation’s 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 simulation’s 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")

Expand Down
9 changes: 9 additions & 0 deletions src/lcg.js
Original file line number Diff line number Diff line change
@@ -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;
}
3 changes: 2 additions & 1 deletion src/simulation.js
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 = [];

Expand Down

0 comments on commit 1e3db41

Please sign in to comment.