js math实现
数学运算基础
JavaScript 提供基础的数学运算符:
- 加法
+ - 减法
- - 乘法
* - 除法
/ - 取余
% - 指数
示例:
const sum = 3 + 5; // 8
const power = 2 3; // 8 (2的3次方)
Math 对象常用方法
JavaScript 内置 Math 对象提供高级数学函数:
取整函数
Math.floor():向下取整Math.ceil():向上取整Math.round():四舍五入Math.trunc():直接截断小数部分
示例:
Math.floor(3.7); // 3
Math.ceil(3.2); // 4
随机数生成
Math.random():生成 [0, 1) 之间的随机数。
扩展为指定范围:function randomInRange(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
三角函数与对数
Math.sin(),Math.cos(),Math.tan()Math.log(),Math.log10()
数值处理与精度
浮点数精度问题
由于二进制浮点数表示,可能出现精度误差:
0.1 + 0.2 === 0.3; // false
解决方案:
- 使用
toFixed()控制小数位数(返回字符串):(0.1 + 0.2).toFixed(2); // "0.30" - 转换为整数运算后再还原:
(0.1 * 10 + 0.2 * 10) / 10; // 0.3
高级数学库
对于复杂计算(如矩阵运算、统计),可使用第三方库:
- Math.js:支持符号计算、单位转换等。
安装:npm install mathjs示例:
import { sqrt, evaluate } from 'mathjs'; sqrt(-4); // 2i (复数结果) evaluate('1.2 * (2 + 4.5)'); // 7.8
实际应用示例
计算两点间距离
function distance(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) 2 + (y2 - y1) 2);
}
生成随机颜色

function randomHexColor() {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
}






