js实现计算
js实现计算的方法
JavaScript提供了多种方式进行数学计算,从基础运算到复杂数学函数均可实现。
基础算术运算
使用标准的算术运算符可直接进行计算:
let sum = 1 + 2; // 加法
let difference = 5 - 3; // 减法
let product = 4 * 6; // 乘法
let quotient = 8 / 2; // 除法
let remainder = 7 % 3; // 取模
let exponentiation = 2 3; // 指数运算
Math对象方法
Math对象提供了更高级的数学运算功能:
Math.sqrt(16); // 平方根
Math.pow(2, 4); // 幂运算
Math.abs(-5); // 绝对值
Math.round(4.6); // 四舍五入
Math.ceil(4.2); // 向上取整
Math.floor(4.9); // 向下取整
Math.max(1, 3, 2); // 最大值
Math.min(1, 3, 2); // 最小值
Math.random(); // 随机数
浮点数精度处理
处理浮点数运算时的精度问题:

// 加法
function add(num1, num2) {
const factor = Math.pow(10, Math.max(num1.toString().split('.')[1]?.length || 0,
num2.toString().split('.')[1]?.length || 0));
return (num1 * factor + num2 * factor) / factor;
}
// 使用decimal.js等库处理高精度计算
表达式求值
通过eval函数或Function构造函数执行字符串表达式:
let result = eval('2 + 3 * 4'); // 14
let calculate = new Function('return 2 + 3 * 4');
calculate(); // 14
科学计算
实现科学计算器功能:
// 三角函数
Math.sin(Math.PI/2); // 正弦
Math.cos(Math.PI); // 余弦
Math.tan(Math.PI/4); // 正切
// 对数函数
Math.log(10); // 自然对数
Math.log10(100); // 以10为底对数
// 其他科学计算
Math.exp(1); // e的幂次
复杂公式计算
处理包含变量的数学公式:

function calculateFormula(a, b, c) {
return (-b + Math.sqrt(b*b - 4*a*c)) / (2*a);
}
货币计算
处理货币计算时的精度问题:
function currencyAdd(a, b) {
return parseFloat((a + b).toFixed(2));
}
大数计算
使用BigInt处理大整数:
const bigNum = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1);
统计计算
实现统计相关计算:
function average(...numbers) {
return numbers.reduce((a, b) => a + b) / numbers.length;
}
function standardDeviation(...numbers) {
const avg = average(...numbers);
const squareDiffs = numbers.map(n => Math.pow(n - avg, 2));
return Math.sqrt(average(...squareDiffs));
}






