SPB Git

Repository Public

prng.ts 2.5 KB 69 lines typescript

1/**2 * Seeded pseudo-random numbers. Everything random in a simulation comes from here, so that the same seed and the3 * same parameters always give exactly the same picture (server render, hydration, export, print).4 */56/** mulberry32: 32-bit state, period 2^32, passes gjrand/PractRand small sets. Returns uniforms in [0, 1). */7export function mulberry32(seed: number): () => number {8  let a = seed >>> 0;9  return () => {10    a = (a + 0x6d2b79f5) >>> 0;11    let t = a;12    t = Math.imul(t ^ (t >>> 15), t | 1);13    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);14    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;15  };16}1718/** FNV-1a hash of a string, 32 bits. */19export function hashString(s: string): number {20  let h = 0x811c9dc5;21  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); }22  return h >>> 0;23}2425/** Independent stream for a named purpose ("weights", "noise"…) derived from the block seed. */26export function deriveSeed(seed: number, salt: string): number {27  let h = (hashString(salt) ^ Math.imul(seed >>> 0, 0x9e3779b1)) >>> 0;28  h = Math.imul(h ^ (h >>> 16), 0x85ebca6b); h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);29  return (h ^ (h >>> 16)) >>> 0;30}3132export interface Rng {33  /** Uniform on [0, 1). */34  next(): number;35  /** Uniform on [a, b). */36  uniform(a: number, b: number): number;37  /** Integer in 0 … n−1. */38  int(n: number): number;39  /** Normal N(mean, sd²) by Box–Muller (both variates of each pair are used). */40  normal(mean?: number, sd?: number): number;41  /** Student-t with integer degrees of freedom, as the ratio Z / sqrt(χ²_df / df). */42  studentT(df: number): number;43}4445export function createRng(seed: number, salt?: string): Rng {46  const next = mulberry32(salt === undefined ? seed : deriveSeed(seed, salt));47  let spare: number | null = null;48  const std = (): number => {49    if (spare !== null) { const z = spare; spare = null; return z; }50    const u1 = 1 - next(); // (0, 1]: the logarithm is finite51    const u2 = next();52    const r = Math.sqrt(-2 * Math.log(u1));53    spare = r * Math.sin(2 * Math.PI * u2);54    return r * Math.cos(2 * Math.PI * u2);55  };56  return {57    next,58    uniform: (a, b) => a + (b - a) * next(),59    int: (n) => Math.min(Math.max(0, Math.floor(n)) - 1, Math.floor(next() * n)),60    normal: (mean = 0, sd = 1) => mean + sd * std(),61    studentT: (df) => {62      const k = Math.max(1, Math.round(df));63      let chi2 = 0;64      for (let i = 0; i < k; i++) { const z = std(); chi2 += z * z; }65      return std() / Math.sqrt(chi2 / k);66    },67  };68}69
Files main
Menu

Theme