JS实现ln
使用Math.log实现自然对数
JavaScript中计算自然对数(ln)可以直接使用Math.log()函数。该函数默认以自然对数底数e为底,等同于数学中的ln函数。
const x = 10;
const result = Math.log(x); // 计算ln(10)
console.log(result); // 输出约2.302585092994046
处理特殊值和边界情况
当参数为负数或0时,Math.log()会返回特定值:
- 参数为0时返回
-Infinity - 参数为负数时返回
NaN - 参数为1时返回0(因为ln(1)=0)
console.log(Math.log(0)); // -Infinity
console.log(Math.log(-1)); // NaN
console.log(Math.log(1)); // 0
自定义ln函数实现
如果需要自定义实现(例如用于教学目的),可以使用泰勒级数展开近似计算:
function customLn(x, iterations = 100) {
if (x <= 0) return NaN;
if (x === 1) return 0;
let sum = 0;
for (let n = 1; n <= iterations; n++) {
const term = Math.pow((x - 1) / x, n) / n;
sum += term;
}
return sum;
}
console.log(customLn(2)); // 约0.6931471805599453
不同底数的对数转换
如果需要计算其他底数的对数,可以通过自然对数转换得到:

- 计算logₐb可以使用公式:ln(b)/ln(a)
function logBase(a, b) {
return Math.log(b) / Math.log(a);
}
console.log(logBase(2, 8)); // 3 (因为2^3=8)
性能注意事项
内置的Math.log()函数经过高度优化,性能远优于自定义实现。在大多数情况下应优先使用内置函数,除非有特殊需求需要自定义实现。






