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.
Code
// 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+200Points of care
Math.sqrt(-1)isNaN, not an exception — check the operand or the result before feeding it downstream.Math.cbrt(-8)returns-2because cube roots of negatives are real;(-8) ** (1/3)andMath.pow(-8, 0.333…)both giveNaNinstead, since IEEE-754 cannot represent the exact 1/3 exponent.Math.sqrt(2) ** 2 === 2isfalse: the rounded root squares back to2.0000000000000004. Reverting a square root through squaring needs a tolerance.Math.hypot(1e200, 1e200)survives where squaring first would overflow toInfinity— compute distances withhypot, notMath.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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free.
Report a problem with this exampleOpens a pre-filled issue on GitHub.