扫码一下
查看教程更方便
math
对象为我们提供数学常量和函数的属性和方法。 与其他全局对象不同,math 不是构造函数。 math 的所有属性和方法都是静态的,可以通过将 math 作为对象来调用而无需创建它。
以下是所有 math 属性及其描述的列表。
序号 | 属性 | 描述 |
---|---|---|
1 | e | 欧拉常数和自然对数的底,大约为 2.718 |
2 | ln2 | 2的自然对数,约0.693 |
3 | ln10 | 10的自然对数,约2.302 |
4 | log2e | e 的以 2 为底的对数,大约为 1.442 |
5 | log10e | e 的以 10 为底的对数,大约为 0.434 |
6 | pi | 圆的周长与其直径之比,大约为 3.14159 |
7 | sqrt1_2 | 1/2 的平方根; 等价于 2 的平方根上的 1,大约为 0.707 |
8 | sqrt2 | 2 的平方根,大约为 1.414 |
基本的指数函数是 math.pow()
,还有计算平方根、立方根和 e 的幂的便捷函数,如下表所示。
序号 | 函数 | 描述 |
---|---|---|
1 | math.pow(x, y) | 返回 x 的 y 次方 |
2 | math.sqrt(x) | 返回数字 x 的平方根 |
3 | math.cbrt(x) | 此方法返回数字 x 的立方根 |
4 | math.exp(x) | 等价于 math.pow(math.e, x) |
5 | math.expm1(x) | 相当于 math.exp(x) – 1 |
6 | math.hypot(x1, x2,...) | 返回参数总和的平方根 |
基本的自然对数函数是 math.log()
。 在 javascript 中,“log”表示“自然对数”。 es6 为方便起见引入了 math.log10
。
序号 | 函数 | 描述 |
---|---|---|
1 | math.log(x) | x 的自然对数 |
2 | math.log10(x) | x 的以 10 为底的对数 |
3 | math.log2(x) | x 的以 2 为底的对数 |
4 | math.log1p(x) | 1 x 的自然对数 |
以下是杂项代数函数及其描述的列表。
序号 | 函数 | 描述 |
---|---|---|
1 | math.abs(x) | x 的绝对值 |
2 | math.sign(x) | x的符号:如果x是负数,–1; 如果 x 为正,则为 1; 如果 x 是 0, 0 |
3 | math.ceil(x) | x的上限:大于等于x的最小整数 |
4 | math.floor(x) | x的下限:小于等于x的最大整数 |
5 | math.trunc(x) | x 的整数部分(去除所有小数位) |
6 | math.round(x) | x 四舍五入到最接近的整数 |
7 | math.min(x1, x2,...) | 返回最小参数 |
8 | math.max((x1, x2,...) | 返回最大参数 |
math 库中的所有三角函数都以弧度而不是度为单位进行运算。
序号 | 函数 | 描述 |
---|---|---|
1 | math.sin(x) | x 弧度的正弦 |
2 | math.cos(x) | x 弧度的余弦 |
3 | math.tan(x) | x 弧度的正切 |
4 | math.asin(x) | x 的反正弦(反正弦)(结果以弧度为单位) |
5 | math.acos(x) | x 的反余弦 (arccos)(结果以弧度为单位) |
6 | math.atan(x) | x 的反正切(arctan)(结果以弧度为单位) |
7 | math.atan2(y, x0) | 从 x 轴到点 (x, y) 的逆时针角度(以弧度为单位) |
math.random()
函数返回一个介于 0(含)和 1(不含)之间的伪随机数。
var value1 = math.random();
console.log("first test value : " value1 );
var value2 = math.random();
console.log("second test value : " value2 );
var value3 = math.random();
console.log("third test value : " value3 );
var value4 = math.random();
console.log("fourth test value : " value4 );
上述代码输出结果如下
first test value : 0.5782922627404332
second test value : 0.5624510529451072
third test value : 0.9336334094405174
fourth test value : 0.4002739654388279