liveBook · Manning

Floating-point arithmetic

As explained in 100 C++ Mistakes and How to Avoid Them

A floating-point value is a numeric representation that approximates a real number using a finite-precision significand and exponent.

Floating-point values approximate real numbers because computers allocate only a limited number of bits to represent them. Most real numbers therefore cannot be expressed precisely, even when the printed result looks familiar. section 12.8

A common mistake is comparing floating-point results with operator==. Dividing 100.0 by 3 produces a value close to 33.3333333333, but not necessarily that exact value, so direct equality can unexpectedly return false. Compare the difference with a suitable epsilon instead. section 12.8

Make conversion explicit

A Rational object can be converted to double for comparison, but the conversion may hide imprecision and invite a misleading equality test. Replace an implicit conversion operator with a named toDouble function so the conversion is visible and type mismatches remain easier to notice. Even then, avoid operator== for floating-point comparisons. section 9.7

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains approximation, limited representation, IEEE 754 behavior, and epsilon comparison, without deriving floating-point internals.
Examples
Uses 100.0 divided by 3 and Rational values such as 1/3 to expose precision and conversion problems.
What it assumes
Assumes basic C++ comparisons and division while teaching why mathematical equality does not guarantee representational equality.
What you can do after
Diagnose precision-related comparison failures and replace direct equality with an epsilon-based comparison.
How it connects
Connects floating-point numbers to rational numbers, implicit conversion, equality comparison, and IEEE 754.

Also explained in

Compare how 20 books explain floating-point arithmetic →

Related concepts

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