Math.sqrt and Math.cbrt Diverge on Negatives

Take roots with Math.sqrt and Math.cbrt: sqrt returns NaN for negatives, cbrt keeps the sign, and neither matches the precision promises of exact math.

JavascriptData Integrity

Code

snippet
// 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));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Points of care

  • Math.sqrt(-1) is NaN, not an exception — check the operand or the result before feeding it downstream.
  • Math.cbrt(-8) returns -2 because cube roots of negatives are real; (-8) ** (1/3) and Math.pow(-8, 0.333…) both give NaN instead, since IEEE-754 cannot represent the exact 1/3 exponent.
  • Math.sqrt(2) ** 2 === 2 is false: the rounded root squares back to 2.0000000000000004. Reverting a square root through squaring needs a tolerance.
  • Math.hypot(1e200, 1e200) survives where squaring first would overflow to Infinity — compute distances with hypot, not Math.sqrt(a*a + b*b).

Using it

Expected printed values: 4 1.4142135623730951 NaN, then 3 -2, then 1024 NaN, then false 2.0000000000000004, then the dist: line with 5 2.828427124746192e+200.

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free.