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.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// 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: NaN

Inside 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

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`.