Math.hypot Skips Intermediate Overflow
Math.hypot sums squares without the intermediate overflow that a hand-written sqrt(x*x + y*y) hits for large components.
Code
// Square-summing by hand overflows for large components
const big = 1e200;
console.log('naive sqrt:', Math.sqrt(big * big + big * big));
console.log('hypot:', Math.hypot(big, big));
// Ordinary cases match the Pythagorean identity
console.log('3-4-5:', Math.hypot(3, 4));
// Any number of dimensions in one call
console.log('3d:', Math.hypot(1, 2, 2));
// Zeros do not disturb the result
console.log('with zeros:', Math.hypot(0, 0, 7, 0));
// hypot of a lone value is its absolute value
console.log('single negative:', Math.hypot(-9));
// Edge semantics: an Infinity anywhere wins, NaN poisons otherwise
console.log('with Infinity:', Math.hypot(Infinity, NaN));
console.log('NaN alone:', Math.hypot(NaN, 3));Output
Captured from a sandboxed run of this snippet in the build pipeline.
naive sqrt: Infinity
hypot: 1.414213562373095e+200
3-4-5: 5
3d: 3
with zeros: 7
single negative: 9
with Infinity: Infinity
NaN alone: NaNInside the snippet
Top-level bindings big hold the demo state — nothing sits inside a function scope.
Putting it to use
The run emits 8 labeled sections — naive sqrt:, hypot:, 3-4-5:, 3d:, with zeros:, single negative:, with Infinity:, NaN alone: — one per step.
Core lines
const big = 1e200;
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `big`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.