js Math.random()在指定的范围内生成随机数 | 您所在的位置:网站首页 › Js手写产生随机数 › js Math.random()在指定的范围内生成随机数 |
最小值n,最大值m Math.random()*(m-n)+n; 由于Math.random() 函数返回一个浮点, 伪随机数在范围[0,1),所以Math.random()*(m-n)+n返回的结果为[n,m)。 n,m为整数,需要[n,m): Math.floor(Math.random()*(m-n))+n; n,m为整数,需要[n,m]:Math.floor(Math.random() * (m- n + 1)) + n; Math.random() * (m- n + 1)的取值为[0,m-n+1),再加n就是[n,m+1),但这样就可能取到(m,m+1)的数,所以向下取整。
Math.round(Math.random()*(m-n))+n; round的舍入其实并不公平,小数部分恰巧等于0.5时会舍入到相邻的在正无穷方向上的整数 (Math.random()*(m-n)).toFixed(num)+n; 原理银行家舍入法,toFixed参数num规定小数的位数,是 0 ~ 20 之间的值,包括 0 和 20,如果省略了该参数,将用 0 代替。 toFixed(银行家舍入法)及其缺陷和解决方法 https://blog.csdn.net/qq_38523017/article/details/83989543 n,m为整数,需要(n,m]: Math.ceil(Math.random()*(m-n))+n;
|
CopyRight 2018-2019 实验室设备网 版权所有 |