liveBook · Manning

Math.hypot

As explained in 100 Java Mistakes and How to Avoid Them

Math.hypot is a Java static method that returns the Euclidean hypotenuse of two arguments with numerical handling designed to reduce overflow and underflow.

`Math.hypot(x, y)` computes a right triangle’s hypotenuse while avoiding a failure mode in the direct Pythagorean expression `Math.sqrt(x * x + y * y)`: intermediate multiplication can underflow even when the final hypotenuse is representable. section 4.2.1

Very small sides

With `x = 3e-200` and `y = 4e-200`, squaring each value can underflow, making the direct square-root calculation return zero rather than the expected `5e-200`. Use `Math.hypot(x, y)` for this calculation instead. section 4.2.1

Use it when numerical range matters:

  • Prefer `Math.hypot(x, y)` over manually squaring and adding tiny floating-point values. section 4.2.1
  • Treat underflow as an edge case: it is uncommon in ordinary work, but it can silently turn a nonzero result into zero. section 4.2.1
double x = 3e-200;
double y = 4e-200;
double hypot = Math.sqrt(x * x + y * y);

Compare the direct Pythagorean calculation with `Math.hypot` when testing extremely small operands. section 4.2.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains an intermediate-multiplication underflow and names `Math.hypot` as the targeted library remedy.
Examples
Contrasts `Math.sqrt(x * x + y * y)` for sides `3e-200` and `4e-200` with the expected `5e-200` result.
What it assumes
Assumes familiarity with floating-point values and the Pythagorean hypotenuse formula.
What you can do after
Apply it via the Java standard library to avoid underflow in hypotenuse calculations.
How it connects
Connects `Math.hypot` with floating-point underflow and the Pythagorean theorem.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.