fix: rng impl
This commit is contained in:
parent
df9698b67b
commit
8d778f9867
|
|
@ -1,6 +1,8 @@
|
||||||
export interface RNG {
|
export interface RNG {
|
||||||
/** 设置随机数种子 */
|
/** 设置随机数种子 */
|
||||||
(seed: number): void;
|
setSeed(seed: number): void;
|
||||||
|
|
||||||
|
getSeed(): number;
|
||||||
|
|
||||||
/** 获取一个 [0,1) 随机数 */
|
/** 获取一个 [0,1) 随机数 */
|
||||||
next(max?: number): number;
|
next(max?: number): number;
|
||||||
|
|
@ -14,33 +16,7 @@
|
||||||
* 这是一个快速、高质量的 32 位 PRNG
|
* 这是一个快速、高质量的 32 位 PRNG
|
||||||
*/
|
*/
|
||||||
export function createRNG(seed?: number): RNG {
|
export function createRNG(seed?: number): RNG {
|
||||||
let currentSeed: number = seed ?? 1;
|
return new Mulberry32RNG(seed);
|
||||||
|
|
||||||
function rng(seed: number): void {
|
|
||||||
currentSeed = seed;
|
|
||||||
}
|
|
||||||
|
|
||||||
rng.next = function(max?: number): number {
|
|
||||||
let t = (currentSeed += 0x6d2b79f5);
|
|
||||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
||||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
||||||
const result = ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
||||||
return max !== undefined ? result * max : result;
|
|
||||||
};
|
|
||||||
|
|
||||||
rng.nextInt = function(max: number): number {
|
|
||||||
return Math.floor(rng.next(max));
|
|
||||||
};
|
|
||||||
|
|
||||||
(rng as any).setSeed = function(seed: number): void {
|
|
||||||
currentSeed = seed;
|
|
||||||
};
|
|
||||||
|
|
||||||
(rng as any).getSeed = function(): number {
|
|
||||||
return currentSeed;
|
|
||||||
};
|
|
||||||
|
|
||||||
return rng;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mulberry32RNG 类实现(用于类型兼容) */
|
/** Mulberry32RNG 类实现(用于类型兼容) */
|
||||||
|
|
|
||||||
|
|
@ -70,12 +70,6 @@ describe('createRNG', () => {
|
||||||
expect(firstSequence).toEqual(secondSequence);
|
expect(firstSequence).toEqual(secondSequence);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work as callable function', () => {
|
|
||||||
const rng = createRNG(42);
|
|
||||||
rng(123);
|
|
||||||
expect(rng.getSeed()).toBe(123);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should generate uniformly distributed integers', () => {
|
it('should generate uniformly distributed integers', () => {
|
||||||
const rng = createRNG(42);
|
const rng = createRNG(42);
|
||||||
const buckets = new Array(10).fill(0);
|
const buckets = new Array(10).fill(0);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue