← 中文资源

简体中文版本

Math.sqrt 与 Math.cbrt 对负数分道扬镳

Math.sqrt 对负数返回 NaN 不抛异常,Math.cbrt 保留符号;(-8)**(1/3) 得 NaN 而立方根函数返回 -2,浮点平方根平方后可能不精确。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

4 1.4142135623730951 NaN
3 -2
1024 NaN
false 2.0000000000000004
dist: 5 1.414213562373095e+200

使用要点

  • 演示输出是带标签的(dist:),每个操作都会留下自己的一行标注。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。

代码示例

// sqrt 只接受非负数,负数返回 NaN 而不抛异常
console.log(Math.sqrt(16), Math.sqrt(2), Math.sqrt(-1));

// cbrt 是唯一接受负数的根函数:立方根符号随操作数
console.log(Math.cbrt(27), Math.cbrt(-8));

// pow 与 ** 等价,负底数带小数指数返回 NaN
console.log(Math.pow(2, 10), (-8) ** (1/3));

// 浮点陷阱:大数平方根可能不精确
console.log(Math.sqrt(2) ** 2 === 2, Math.sqrt(2) ** 2);

// 距离计算用 hypot 避免中间值溢出
console.log("dist:", Math.hypot(3, 4), Math.hypot(1e200, 1e200));