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}`);

结果:
这里写图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值