feat: seeded RNG with per-label deterministic rolls

This commit is contained in:
2026-06-12 13:54:40 +00:00
parent fe28d8ddcb
commit 52d5008cdf
2 changed files with 60 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest';
import { hash32, makeRng, rollFor } from '../src/sim/rng.js';
describe('rng', () => {
it('hash32 is deterministic and spreads', () => {
expect(hash32('abc')).toBe(hash32('abc'));
expect(hash32('abc')).not.toBe(hash32('abd'));
});
it('makeRng produces a deterministic sequence in [0,1)', () => {
const a = makeRng(42), b = makeRng(42);
for (let i = 0; i < 100; i++) {
const v = a();
expect(v).toBe(b());
expect(v).toBeGreaterThanOrEqual(0);
expect(v).toBeLessThan(1);
}
});
it('rollFor depends on seed and label, independently', () => {
expect(rollFor('s1', 'x')).toBe(rollFor('s1', 'x'));
expect(rollFor('s1', 'x')).not.toBe(rollFor('s1', 'y'));
expect(rollFor('s1', 'x')).not.toBe(rollFor('s2', 'x'));
});
it('rollFor is roughly uniform', () => {
let sum = 0;
for (let i = 0; i < 2000; i++) sum += rollFor('u', `l${i}`);
expect(sum / 2000).toBeGreaterThan(0.45);
expect(sum / 2000).toBeLessThan(0.55);
});
});