Math.random() - JavaScript Math 对象
Math.random()
Math.random()
函数返回一个浮点,伪随机数在范围[0,1),也就是说,从0(包括0)往上,但是不包括1(排除1),然后您可以缩放到所需的范围。实现将初始种子选择到随机数生成算法;它不能被用户选择或重置。
[0,1)===[即从0(包含0)到...1但不包括1(排除1)。
[0,1)===左闭右开区间
Math.random()
不能提供像密码一样安全的随机数字
不能使用它们来处理有关安全的事情。使用Web Crypto API 来代替,和更精确的window.crypto.getRandomValues()
方法.
语法
Math.random()
返回参数
一个浮点型伪随机数字,在0
(包括0)和1
(不包括)之间。
示例
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below(excluding the one forMath.random()
itself)aren't exact. If extremely large bounds are chosen(253 or higher), it's possible inextremelyrare cases to calculate the usually-excluded upper bound.(注:round-to-nearest-even采用最近舍入的去偶数舍入的方式,对.5的舍入上,采用取偶数的方式)
请注意,由于 JavaScript 中的数字是 IEEE 754 浮点数字,具有最近舍入( round-to-nearest-even)的行为,因此以下函数的范围(不包括Math.random()本身)并不准确。如果选择了非常大的边界(253 或更高),在极罕见的情况下会计算通常-排除(usually-excluded)的上界。
IEEE 754标准的默认模式是最近舍入(舍入为最接近的偶数),它与四舍五入不同的是,对.5的舍入上采用取偶数的方式,即round-to-nearest-even,如:
Round to nearest even:Round(0.5)= 0; Round(1.5)= 2; Round(2.5)= 2;Round(3.5)= 4;
即:"四舍六入五取偶"
“五取偶”的规则:当小数部分恰为0.5时,若个位是奇数则入,若个位是偶数则舍,总之让个位变成偶数。
得到一个大于等于0,小于1之间的随机数
function getRandom() { return Math.random(); }
得到一个两数之间的随机数
这个例子返回了一个在指定值之间的随机数。这个值不小于min
(有可能等于),并且小于(不等于)max
。
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }
得到一个两数之间的随机整数
这个例子返回了一个在指定值之间的随机整数。这个值不小于min
(如果min
不是整数,则不小于min
的向上取整数),且小于(不等于)max
。
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值 }
也许很容易想到用Math.round()
来实现,但是这会导致你的随机数处于一个不均匀的分布,这可能不符合你的需求。
得到一个两数之间的随机整数,包括两个数在内
上一个例子提到的函数getRandomInt()
结果范围包含了最小值,但不含最大值。如果你的随机结果需要同时包含最小值和最大值,怎么办呢?getRandomIntInclusive()
函数可以实现。
function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 }
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!