今天写动态流星雨的时候有用到正负随机数这种东西,因为js的随机数的取值范围是[0,1)之间,而需求的区间需要[-100,200)之间,一时间犯了难,想不起来怎么取负数。就查阅了一下大家的做法。这里做个笔记,把需求和变式都整理一下。
1、取[0,10) 和 (0,10]
基础变式,区别在于取整的方式。
向下取整
Math.floor(Math.random() * 10) // [0,10)
向上取整
Math.ceil(Math.random() * 10) // (0,10]
2、取[0,10]
跟第一个不同,因为Math.random()的取值范围是左闭右开,所以他直接乘以10是取不到10的,这里稍微改一下
向下取整
Math.floor(Math.random() * 11) // [0,10]
向上取整
Math.ceil(Math.random() * 11) - 1 // [0,10]
3、取[10,20)和[10,20]
Math.floor(Math.random() * 10 ) + 10 // [10,20)
Math.floor((Math.random() + 1) * 10 ) // [10,20)
Math.floor(Math.random() * 11 ) + 10 // [10,20]
Math.floor((Math.random() + 1) * 11 ) // [11,20]
注意这种方式是取不到10的
4、取[-5,5)
Math.floor(Math.random() * 10) - 5 // [-5,5)
Math.floor((Math.random() - 0.5) * 10 ) // [-5,5)
5、取[-3,10)
Math.floor(Math.random() * 13) - 3 // [-3,10)
总结一下,随机数取值的公式应该是:
Math.random() * ( |max| + |min|) + min // [ min , max ) max为最大值,min为最小值
最后,我能想到的变式就这些,如果有什么错误或者缺漏的,请告诉我,我会马上更新上来。
我需要创建一个
随机
-1或1来乘以一个已经存在的数字。问题是我目前的
随机
函数产生-1,0或1.这样做的最有效方法是什么?
用Math.random()即可。如果< 0.5,那么-1,否则1:
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
Math.round(Math.random())会给你0或1,
0小于0.5,三目运算结果为true,那就
取
值-1,
1大于0.5,三目运算结果为false,那就
取
值1。
或者这样:
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
js
随机数
作者 | 阮一峰Math是 JavaScript 的原生对象,提供各种数学功能。该对象不是构造函数,不能生成实例,所有的属性和方法都必须在Math对象上调用。1、静态属性Math对象的静态属性,提供以下一些数学常数。Math.E:常数e。Math.LN2:2 的自然对数。Math.LN10:10 的自然对数。Math.LOG2E:以 2 为底的e的对数。Math.LOG10E:以 10 ...
前言:
JS
没有现成的函数,能够直接生成指定范围的
随机数
。但是它有个函数:Math.random() 这个函数可以生成 [0,1) 的一个
随机数
。利用它,我们就可以生成指定范围内的
随机数
。而涉及范围的话,就有个边界值的问题。这样就包含四种情况:1)min ≤ r ≤ max (一般这种比较常见)2)min ≤ r < max3) min < r ≤ max4)min < r &...
parseInt()对于正数和负数,都是去掉小数点部分,保留整数部分。
math.round对于正数和负数,为四舍五入,与数值大小无关,仅对数值本身四舍五入。如-1.4,
取
了之后是-1.
Math.floor对于
正负
数,以数值大小判断,即在数轴上判断。即使有小数,也往数值小的整数
取
。
Math.ceil对于
正负
数, 以数值大小判断,即在数轴上判断。只要带有小数,就往数值大的整数
取
。
以上方法,对于0,返回0。对于undefined或null或空字符串或非纯数字的字符串等,返回NaN