Floating point comparison problems in numbers.

Two Numbers That Should Be Equal Usually Are Not

I spent three weeks of my life in a high-frequency trading shop chasing a ghost that refused to die. The logic was sound, the math was perfect, and the unit tests passed every single time—until we hit production. It turned out we were falling victim to classic floating point comparison problems, where a value that looked like `0.1` in the debugger was actually `0.10000000149011612` in the registers. It’s the kind of subtle, silent betrayal that makes you want to throw your mechanical keyboard across the room and go back to working on analog circuits where a signal is either high or it isn’t.

I’m not here to give you a lecture on IEEE 754 standards or recite textbook definitions that won’t help you when your production environment starts hemorrhaging money. Instead, I’m going to show you how the hardware actually handles these values and how to write code that doesn’t rely on mathematical luck. We’re going to look at epsilon checks, scaling, and the specific edge cases where the compiler’s optimizations might just decide to ruin your day.

Table of Contents

The Ieee 754 Standard Explained the Rules That Bite

The Ieee 754 Standard Explained the Rules That Bite.

Most people treat `float` and `double` as if they were real numbers. They aren’t. They are approximations governed by the IEEE 754 standard, and if you don’t respect the spec, the spec will punish you. The core of the issue lies in the binary representation of decimals; our base-10 world doesn’t map cleanly to base-2. When you type `0.1` into your source code, you aren’t storing exactly one-tenth. You are storing the closest possible approximation the hardware can manage.

This approximation is where the friction begins. Because we have a finite number of bits to represent an infinite continuum of values, we are constantly dealing with rounding errors in computer science that accumulate like silt in a riverbed. Every arithmetic operation—every addition, every multiplication—introduces a tiny bit of noise. By the time you reach your third or fourth calculation, the “exact” value you expected has drifted into a different neighborhood entirely. It’s not a bug in your logic; it’s a fundamental constraint of the hardware.

Binary Representation of Decimals the Lie You Believe

Binary Representation of Decimals the Lie You Believe

The core of the problem isn’t your math; it’s the base-2 system. We think in base-10, where $0.1$ is a clean, simple fraction. But in the binary representation of decimals, $0.1$ is a repeating fraction, much like $1/3$ is $0.333dots$ in our decimal system. You can never truly write it down perfectly in a finite number of bits. When you assign `float x = 0.1f;`, you aren’t storing $0.1$. You are storing the closest possible approximation that the hardware can manage.

This is where the lie becomes dangerous. You see `0.1` in your debugger and assume the value is exact, but you’re looking at a rounded shadow. These tiny, inherent inaccuracies are the primary source of rounding errors in computer science. They accumulate silently. You might perform a dozen trivial additions, and suddenly, a value you expected to be exactly `1.0` is actually `1.0000000000000002`. If your code relies on `if (x == 1.0)`, that check will fail, and you’ll spend three hours staring at a logic gate that is technically perfect but mathematically delusional.

Survival Strategies for the Floating Point Minefield

  • Stop using `==` immediately. If you find yourself writing `if (a == b)` with any type of float, you aren’t writing logic; you’re writing a prayer. Use an epsilon-based comparison instead.
  • Define your epsilon based on the scale of your numbers. A hardcoded `1e-9` is fine for unit tests in a vacuum, but it will fail you if you’re dealing with astronomical distances or subatomic particles. Scale your tolerance or prepare for silent failures.
  • Prefer `std::isless` or `std::isgreater` when you need to handle NaNs explicitly. Standard relational operators like “ will simply return `false` when a NaN is involved, which can lead to logic paths that should be impossible to reach.
  • Use `std::nextafter` if you need to find the smallest possible increment. If you are trying to find the “next” representable number to test a boundary, don’t just add a tiny constant; use the hardware-defined successor to avoid falling into the gap between representable values.
  • Keep your accumulation math sane. If you are summing a massive array of floats, the error doesn’t just add up—it compounds. For high-precision requirements, use Kahan summation or at least aggregate into a `double` before casting back to `float`.

The TL;DR for Not Shipping Broken Math

Stop using `==` with floats. If you treat a floating-point number like an integer, you’re ignoring the reality of rounding errors and asking for a production bug.

Understand that decimal precision is a lie. Most “simple” base-10 decimals cannot be represented exactly in binary, meaning your starting value is already slightly “wrong.”

Use an epsilon. When you need to check for equality, define a tolerance threshold that accounts for the inevitable drift inherent in IEEE 754 arithmetic.

Stop Guessing, Start Testing

We’ve established that floating point numbers aren’t real decimals; they are approximations masquerading as precision. You can’t treat them like integers and expect the universe to remain stable. Between the inherent limitations of IEEE 754 and the way binary representation turns a simple 0.1 into an infinite repeating fraction, your `if (a == b)` statements are essentially Russian roulette with your program’s logic. Whether you’re dealing with catastrophic cancellation or simple rounding errors, the takeaway is the same: you must embrace epsilon-based comparisons or use specialized decimal libraries if you actually care about the result. Stop treating the hardware like a math textbook and start treating it like the approximation engine it actually is.

Writing robust code in C++ isn’t about memorizing every corner case in the standard; it’s about developing a healthy suspicion of what the machine is doing under the hood. When you stop trusting your eyes and start respecting the underlying bit patterns, you move from being a coder who gets lucky to a systems programmer who builds things that last. The bugs are already there, hiding in the precision gaps. Your job isn’t just to write logic, but to outsmart the hardware before it outsmarts you. Now, go check your equality operators.

About Ruaridh Kensington-Oyelaran

C++ rewards people who know what the compiler is allowed to do. I write about the rules that bite, the ones nobody mentions until you have already shipped the bug.

More From Author

Structured concurrency ideas: task scope management.

No Task Should Outlive the Scope That Started It