math/prefer-math-hypot
enforce the use of Math.hypot() instead of other hypotenuse calculations
- ⚙️ This rule is included in
"plugin:math/recommended"
. - 🔧 The
--fix
option on the command line can automatically fix some of the problems reported by this rule. - 💡 Some problems reported by this rule are manually fixable by editor suggestions.
📖 Rule Details
This rule aims to enforce the use of Math.hypot()
instead of other hypotenuse calculations.
Math.hypot()
provides several advantages over manual Pythagorean theorem calculations:
- Overflow protection: Avoids intermediate overflow when dealing with large numbers
- Underflow protection: Prevents precision loss with very small numbers
- Numerical stability: Uses algorithms optimized for floating-point arithmetic
- Clarity: Expresses the mathematical intent more clearly
- Variable arguments: Supports any number of dimensions, not just 2D
The Numerical Stability Problem
Manual calculations can suffer from overflow/underflow issues:
js
// These can overflow with large numbers
const large = 1e200;
Math.sqrt(large * large + large * large) // Infinity (overflow)
// Math.hypot handles this correctly
Math.hypot(large, large) // 1.4142135623730951e+200 (correct)
// Similarly for very small numbers (underflow)
const small = 1e-200;
Math.sqrt(small * small + small * small) // 0 (underflow)
Math.hypot(small, small) // 1.4142135623730951e-200 (correct)
🔧 Options
Nothing.
📚 Further reading
🚀 Version
This rule was introduced in eslint-plugin-math v0.6.0