@4bitlabs/pcg-xsh-rr
v1.0.0
Published
A simple seedable pseudo-random-number generator, PCG-XSH-RR, for typescript.
Readme
@4bitlabs/pcg-xsh-rr
A TypeScript bigint implementation of PCG-XSH-RR.
[!WARNING] You probably do not want to use this library. Prefer a more rigorous library like pure-rand for all your pseduo-random-number generation needs. This package is for my own edification and learning purposes.
Example
import { createPcg32 } from '@4bitlabs/pcg-xsh-rr';
const SEED = Date.now();
const rng = createPcg32(SEED);
rng.next(); // returns a number between 0x0000_0000 and 0xFFFF_FFFFDistribution helpers:
import {
createPcg32,
float64,
float32,
intRange,
pickFrom,
} from '@4bitlabs/pcg-xsh-rr';
const SEED = Date.now();
const rng = createPcg32(SEED);
console.log(float64(rng)); // a number in the range of [0,1). 53-bits of entropy
console.log(float32(rng)); // a number in the range of [0,1). 23-bits of entropy
console.log(intRange(rng, 1, 6)); // an integer in the range of [1, 6]
console.log(pickFrom(rng, ['apple', 'banana', 'carrot'])); // one of 'apple' | 'banana' | 'carrot'Other Random Provider wrappers
import { mathRand, cryptoRand, intRange } from "./builtin";
intRange(mathRand, 1, 6); // use Math.random() for a die roll
pickFrom(cryptoRand, ['apple', 'banana', 'carrot']); // use crypto-secure random source[!NOTE] Again, you probably dont want to be doing either of these things. But again, if you are experimenting and learning about random-number generators, knock yourself out!
Caveats
[!WARNING] This library uses
bigintfor the internal state of the pRNG. This makes it rather slow, and could be optimized by implementinguint64math ontop ofint32safe JavaScript operations. But, that would a) be sustantially more complex and unreadable b) there are other libraries, see above, that do that already and better. So, just use those. Thanks!
