Egret -- 自己寫的隨機類

由於需要,自己寫了一個隨機類,拿去用吧。


/**
 * 隨機值生成器
 */
class Random {
    private a: number;
    private b: number;
    private m: number;
    private x: number;

    constructor(seed: number){
        let p = 2
        let q = 3
        this.a = 4 * p + 1
        this.b = 2 * q + 1
        this.m = 1048576
        this.x = seed
    }

    /**
     * 產生下一個隨機值(整數)
     * @param min 隨機範圍最小值
     * @param max 隨機範圍最大值
     * @return 隨機值
     */
    public nextInt(min: number, max: number): number {
        return Math.round(this.nextFloat(min, max));
    }

    /**
     * 產生下一個隨機值(浮點數)
     * @param min 隨機範圍最小值
     * @param max 隨機範圍最大值
     * @return 隨機值
    */
    public nextFloat(min: number, max: number): number {
        let x0 = this.x
        let x1 = this.a * x0 + this.b;
        // 取模
        this.x = x1 - Math.floor(x1 / this.m) * this.m;
        let r = max - min
        return min + (this.x / this.m * r)
    }
}

測試:

let random = new Random(123456);
let countFloat = 0;
let countInt = 0;
for(var i = 0; i < 200; i++){
    countInt += random.nextInt(0, 100);
    countFloat += random.nextFloat(0, 100);
}

console.log(`countFloat:${countFloat}`);
console.log(`countInt:${countInt}`);

let random1 = new Random(123456);
countFloat = 0;
countInt = 0;
for(var i = 0; i < 200; i++){
    countInt += random1.nextInt(0, 100);
    countFloat += random1.nextFloat(0, 100);
}
console.log(`countFloat:${countFloat}`);
console.log(`countInt:${countInt}`);

結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章