Skip to content

Commit

Permalink
✨ Clone from state on xorshift128plus (#697)
Browse files Browse the repository at this point in the history
Follow-up of #694
  • Loading branch information
dubzzz committed Mar 20, 2024
1 parent 6a16bfe commit c60c828
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/generator/XorShift.ts
Expand Up @@ -64,8 +64,22 @@ class XorShift128Plus implements RandomGenerator {
this.s11 = ns11;
this.s10 = ns10;
}
getState(): readonly number[] {
return [this.s01, this.s00, this.s11, this.s10];
}
}

function fromState(state: readonly number[]): RandomGenerator {
const valid = state.length === 4;
if (!valid) {
throw new Error('The state must have been produced by a xorshift128plus RandomGenerator');
}
return new XorShift128Plus(state[0], state[1], state[2], state[3]);
}

export const xorshift128plus = function (seed: number): RandomGenerator {
return new XorShift128Plus(-1, ~seed, seed | 0, 0);
};
export const xorshift128plus = Object.assign(
function (seed: number): RandomGenerator {
return new XorShift128Plus(-1, ~seed, seed | 0, 0);
},
{ fromState },
);
2 changes: 2 additions & 0 deletions test/unit/generator/XorShift.spec.ts
Expand Up @@ -92,6 +92,8 @@ describe('xorshift128plus', () => {
);
});
it('Should return the same sequence given same seeds', () => fc.assert(p.sameSeedSameSequences(xorshift128plus)));
it('Should return the same sequence when built from state', () =>
fc.assert(p.clonedFromStateSameSequences(xorshift128plus)));
it('Should return the same sequence if called twice', () => fc.assert(p.sameSequencesIfCallTwice(xorshift128plus)));
it('Should generate values between -2**31 and 2**31 -1', () => fc.assert(p.valuesInRange(xorshift128plus)));
it('Should not depend on ordering between jump and next', () => fc.assert(p.noOrderNextJump(xorshift128plus)));
Expand Down

0 comments on commit c60c828

Please sign in to comment.