liveBook · Manning

Underflow

As explained in 100 Java Mistakes and How to Avoid Them

Underflow is a numerical condition in which a computed result falls below the representable range of its numeric type, potentially losing precision or becoming zero.

Underflow occurs when a float or double computation produces a value too close to zero to represent through its intermediate operations. Unlike integer overflow, it arises with extremely small floating-point values and may silently turn a nonzero expected result into zero. section 4.2.1

A tiny hypotenuse

For x = 3e-200 and y = 4e-200, Math.sqrt(x * x + y * y) returns zero rather than the expected 5e-200: squaring the inputs underflows before the square root runs. Use Math.hypot(x, y), which is designed to avoid this failure. section 4.2.1

Treat underflow pragmatically:

  • Check calculations involving extremely small float or double values when a zero result would be significant. section 4.2.1
  • Prefer Math.hypot for hypotenuse calculations instead of manually squaring very small operands. section 4.2.1
  • Ignore it only when the application can safely tolerate the rare extremely-small-number case. section 4.2.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains intermediate multiplication underflow through a focused hypotenuse example and a library alternative.
Examples
Uses 3e-200 and 4e-200 inputs whose manual hypotenuse computation yields zero instead of 5e-200.
What it assumes
Assumes familiarity with Java float or double arithmetic and square-root expressions.
What you can do after
Evaluate/understand when an extremely small floating-point calculation can collapse to zero and choose Math.hypot.
How it connects
Connects floating-point numbers, the Pythagorean theorem, and Math.hypot.

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.