如:

1~10 之间的随机数,那么他们的取值范围是

 

整数

区间

概率

1

[0,1)

0.1

2

[1,2)

0.1

3

[2,3)

0.1

4

[3,4)

0.1

5

[4,5)

0.1

6

[5,6)

0.1

7

[6,7)

0.1

8

[7,8)

0.1

9

[8,9)

0.1

10

[9,10)

0.1

 

如果调整2的概率为0.5,那么1~10之间的随机数取值区间与其它值的概率都会发现变化 如下:

最小取值范围 = 0

最大取值范围 = 最小取值范围  + 概率 * 10(分成10份)

 

整数

区间

概率

1

[0,0.55)

≈ 0.055

2

[0.55,5)

0.5

3

[5,5.55)

≈ 0.055

4

...

≈ 0.055

5

...

≈ 0.055

6

...

≈ 0.055

7

...

≈ 0.055

8

...

≈ 0.055

9

...

≈ 0.055

10

...

≈ 0.055

 

 

然后调用随机函数生成1~10之间的随机数,如果生成的随机数在某个整数的取值范围内,那么就输出当前整数。

 

/*
 * @Author: 破壳而出的蝌蚪
 * @博客:https://www.cnblogs.com/whnba/ 
 * @Date: 2019-01-03 15:03:33 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-01-03 15:04:17
 */

'use strict';

class GLRandom {
    /**
     * 构造函数
     * @param {number} min  最小整数值
     * @param {number} max  最大整数值
     * @param {Map} percentage 概率数 [值,百分比]
     */
    constructor(min, max, percentage = new Map()) {
        this.min = Math.trunc(min);
        this.max = Math.trunc(max);
        this.MATH_RANGE = 100;  // 分成100份
        this.percentage = percentage;
    }

    get percentage() {
        if (!this._percentage) {
            this._percentage = new Map();
        }
        return this._percentage;
    }

    /**
     * 分配比例
     * @param {Map} map 设置 值-百分比
     */
    set percentage(map) {
        let result = Array.from(map.values()).reduce((p, v, a) => {
            return p - v;
        }, 1);
        for (let i = this.min; i < this.max; i++) {
            if (map.has(i)) {
                this.percentage.set(i, map.get(i));
            } else {
                this.percentage.set(i, result / (this.max - this.min - map.size));
            }
        }
    }

    /**
     * 根据比例生成取值范围
     */
    range() {
        let [start, random, keys] = [0, this.MATH_RANGE, Array.from(this.percentage.keys())];
        for (let i = 0; i < keys.length; i++) {
            let temp = this.percentage.get(keys[i]);
            this.percentage.set(keys[i], [start, start += temp * random]);
        }
    }

    /**
     * 生成随机数
     */
    create() {
        let num = Math.random() * this.MATH_RANGE;
        for (let data of this.percentage.entries()) {
            if (num >= data[1][0] && num < data[1][1]) {
                return data[0];
            }
        }
        return null;
    }
}

 

 

// 样本
{
    // 随机数范围 :40~900 
    let random = new GLRandom(40, 100);

    // 调整概率
    random.percentage = new Map([
        [41,0.2],   // 调整值为41的数值,概率为20%  
        [46,0.5],   // 调整值为46的数值,概率为50%  
        [90,0.05]   // 调整值为90的数值,概率为5%  
    ]);

    // 生成值区间
    random.range();

    // 生成概率随机数
    console.log(random.create());
}

百度经验地址:https://jingyan.baidu.com/article/5553fa827bfe7d65a239341d.html

源码地址:https://pan.baidu.com/s/1ieOhaYe34nAhA8jfHhFzaw

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程