美文网首页
JS生成指定范围随机数

JS生成指定范围随机数

作者: rLydia | 来源:发表于2019-08-24 20:10 被阅读0次

    相关面试题:
    (01) 用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值

    相关知识:

     Math.random()    // [0,1) 伪随机数 浮点数
     Math.ceil()      // 向上取整
     Math.floor()     // 向下取整
     Math.round()     // 四舍五入
     parseInt()    // 取整数部分
    
     Math.ceil(Math.random()*10);    // [0,10] 但基本相当于获取从1到10的随机整数,因取0的概率极小。
     Math.floor(Math.random()*10);   // [0,10) 可均衡获取0到9的随机整数。
     Math.round(Math.random()*10);   // [0,10] 基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
     // 因结果在0~0.4 为0,0.5到1.4为1...8.5到9.4为9,9.5到9.9为10。所以头尾的分布区间只有其他数字的一半。
    
     Math.random()  // [0, 1) 随机浮点数
     Math.random()*(m-n) + n  // [n, m) 随机浮点数; m-n可看为是length
     Math.round(Math.random())    // 随机获取0或1,获取几率较均衡
     Math.floor(Math.random()*m)  // 随机获取[0,m)、即[0, m-1]之间整数,获取均衡
     Math.floor(Math.random()*m)+1  // 随机获取[1,m) 、即[1, m-1]之间整数,获取均衡
    

    生成指定范围内的随机整数:

    [min, max)

     parseInt(Math.random()*(max-min)) + min 
     Math.floor(Math.random()*(max-min)) + min
    

    [min, max] -> 相当于[min, max+1)

     Math.floor(Math.random()*(max+1-min))+min
    

    (min, max]

     Math.ceil(Math.random()*(max-min)) + min
    

    (min, max) -> 相当于[min+1, max)

     Math.floor(Math.random()*(max-(min+1)) + min+1
    

    参考:
    https://www.cnblogs.com/starof/p/4988516.html
    https://www.hangge.com/blog/cache/detail_1872.html

    相关文章

      网友评论

          本文标题:JS生成指定范围随机数

          本文链接:https://www.haomeiwen.com/subject/mcmqectx.html