Don't compare computed doubles with ==. Use a relative tolerance: std::fabs(a - b) <= 1e-9 * std::max(std::fabs(a), std::fabs(b)), and add an absolute tolerance such as 1e-12 when the values can be near zero. To check for NaN use std::isnan(x), because nan == nan is always false.
0.1 + 0.2 == 0.3 is false in C++ because none of those three numbers is stored exactly: a double holds the nearest binary fraction, and the sum lands one step away from the nearest double to 0.3. The fix is to ask whether two values are close enough, and the hard part is the meaning of "close": a fixed epsilon is too strict for large numbers and too loose for tiny ones. The sections below build a tolerance test that works at every scale, show why == and numeric_limits::epsilon() fail, count ULPs, handle NaN, infinity and -0.0, and sort values that contain NaN. Each example runs on this page: hit Run, then edit the numbers and run it again.
1A relative tolerance with an absolute floorRecommended
The error in a floating-point result grows with the size of the numbers, so the tolerance should too. Scale it by the larger magnitude of the two values: a relative tolerance of 1e-9 means "equal in the first nine significant digits", whether the values are near 0.3 or near 3 billion. Near zero that scale shrinks to nothing, so a second, absolute tolerance sets a floor. This is the test Python ships as math.isclose, with the same defaults, and it handles the special values: two equal infinities match, and NaN matches nothing.
#include <algorithm> #include <cmath> #include <iostream> #include <limits> #include <numbers> // Equal when a and b differ by at most rel_tol of the larger magnitude, // or by at most abs_tol (the only test that works at or near zero) bool approx_equal(double a, double b, double rel_tol = 1e-9, double abs_tol = 0.0) { if (a == b) { return true; // exact match, including two equal infinities } if (std::isinf(a) || std::isinf(b)) { return false; // inf - x is inf, which no tolerance should accept } double diff = std::fabs(a - b); // NaN makes every <= below false double scale = std::max(std::fabs(a), std::fabs(b)); return diff <= std::max(rel_tol * scale, abs_tol); } int main() { std::cout << std::boolalpha; double sum = 0.1 + 0.2; std::cout << "sum == 0.3: " << (sum == 0.3) << '\n'; std::cout << "approx_equal(sum, 0.3): " << approx_equal(sum, 0.3) << '\n'; // Relative: the same default works for large values std::cout << "1000.1 + 1000.2 vs 2000.3: " << approx_equal(1000.1 + 1000.2, 2000.3) << '\n'; // Really different values stay different std::cout << "1.0 vs 1.0001: " << approx_equal(1.0, 1.0001) << '\n'; std::cout << "with rel_tol 1e-3: " << approx_equal(1.0, 1.0001, 1e-3) << '\n'; // Near zero a relative test fails: give an absolute tolerance too double s = std::sin(std::numbers::pi); // should be 0, is about 1.2e-16 std::cout << "sin(pi) vs 0: " << approx_equal(s, 0.0) << '\n'; std::cout << "with abs_tol 1e-12: " << approx_equal(s, 0.0, 1e-9, 1e-12) << '\n'; // NaN equals nothing, infinity equals only itself double nan = std::numeric_limits<double>::quiet_NaN(); double inf = std::numeric_limits<double>::infinity(); std::cout << "nan vs nan: " << approx_equal(nan, nan) << '\n'; std::cout << "inf vs inf: " << approx_equal(inf, inf) << '\n'; std::cout << "inf vs 1e308: " << approx_equal(inf, 1e308) << '\n'; }
Output
The sum fails == (sum == 0.3: false) and passes the tolerance test (approx_equal(sum, 0.3): true), and the same default accepts 1000.1 + 1000.2 vs 2000.3: true, where a fixed epsilon fails (section 3). Values that really differ stay different: 1.0 vs 1.0001: false, until you loosen rel_tol to 1e-3. Near zero, relative tolerance alone says sin(pi) vs 0: false, because the scale is the tiny value itself; with abs_tol set to 1e-12 it is true. There is no universal abs_tol: pick it from your units (a millimetre, a cent, a pixel). The infinity guard matters: without it, inf - 1e308 is inf and so is the scaled tolerance, so inf <= inf would call them equal. For float, use a looser rel_tol such as 1e-5: it keeps only about 7 significant digits.
2Why == fails: what a double really stores
A double has 53 significant bits, a float 24. Decimal fractions such as 0.1, 0.2 and 0.7 have no exact binary form, so each literal is rounded to the nearest value that fits, and every operation rounds again. Default std::cout output shows only 6 significant digits, which is why the two sides of a failing == often print the same. Print 17 digits, or use std::format, to see the real values.
#include <format> #include <iomanip> #include <iostream> int main() { double sum = 0.1 + 0.2; // cout rounds to 6 significant digits, which hides the difference std::cout << sum << " vs " << 0.3 << '\n'; // 17 significant digits show the doubles that are really stored std::cout << std::setprecision(17) << sum << " vs " << 0.3 << '\n'; // std::format prints the shortest text that reads back as the same double std::cout << std::format("{} vs {}\n", sum, 0.3); // Rounding errors add up: ten times 0.1 is not 1 double total = 0.0; for (int i = 0; i < 10; ++i) { total += 0.1; } std::cout << std::format("total = {}, total == 1.0: {}\n", total, total == 1.0); // float vs double: 0.7f is rounded to 24 bits, 0.7 to 53 bits, // and the comparison converts the float to double float f = 0.7f; std::cout << std::format("f < 0.7: {}, f == 0.7f: {}\n", f < 0.7, f == 0.7f); std::cout << std::format("0.7f as a double: {}\n", static_cast<double>(f)); // == is exact and safe when every value involved is exact: // small integers and sums of powers of two std::cout << std::format("0.5 + 0.25 == 0.75: {}\n", 0.5 + 0.25 == 0.75); std::cout << std::format("3.0 * 7.0 == 21.0: {}\n", 3.0 * 7.0 == 21.0); // ...until the integers pass 2^53, where doubles skip odd numbers double big = 9007199254740992.0; // 2^53 std::cout << std::format("2^53 + 1 == 2^53: {}\n", big + 1.0 == big); }
Output
The first line prints 0.3 vs 0.3 for two different doubles. With 17 digits they are 0.30000000000000004 vs 0.29999999999999999, and std::format prints the shortest text that reads back exactly: 0.30000000000000004 vs 0.3. Errors accumulate, so adding 0.1 ten times gives total = 0.9999999999999999. Mixing types is its own trap: f < 0.7: true because the comparison widens the float to 0.699999988079071, while f == 0.7f is true because both sides were rounded to float the same way. And == is fine when every value is exact: 0.5 + 0.25 == 0.75: true and 3.0 * 7.0 == 21.0: true, as long as whole numbers stay at or below 2^53; past it, 2^53 + 1 == 2^53: true.
3The epsilon trap: numeric_limits::epsilon()
The most common answer to this question is std::fabs(a - b) < std::numeric_limits<double>::epsilon(). It looks official, but epsilon() is not a comparison tolerance: it is the gap between 1.0 and the next double. That gap grows with the size of the numbers and shrinks towards zero, so a fixed epsilon only means "one rounding step" for values between 1 and 2.
#include <cmath> #include <format> #include <iostream> #include <limits> // The common but wrong test: one fixed absolute epsilon for every value bool eps_equal(double a, double b) { return std::fabs(a - b) < std::numeric_limits<double>::epsilon(); } int main() { double eps = std::numeric_limits<double>::epsilon(); std::cout << std::format("double epsilon: {}\n", eps); float feps = std::numeric_limits<float>::epsilon(); std::cout << std::format("float epsilon: {}\n", feps); // epsilon is the gap between 1.0 and the next double, so near 1 it works std::cout << std::format("gap above 1.0: {}\n", std::nextafter(1.0, 2.0) - 1.0); std::cout << std::format("0.1 + 0.2 vs 0.3: {}\n", eps_equal(0.1 + 0.2, 0.3)); // Above 2 the gap between neighbouring doubles is bigger than epsilon, // so a result one rounding step off already fails double gap = std::nextafter(300.0, 400.0) - 300.0; std::cout << std::format("gap above 300.0: {}\n", gap); bool same = eps_equal(100.1 + 200.2, 300.3); std::cout << std::format("100.1 + 200.2 vs 300.3: {}\n", same); // Near zero epsilon is far too loose: values 1000 times apart pass, // and so does any tiny value against 0 std::cout << std::format("1e-20 vs 1e-17: {}\n", eps_equal(1e-20, 1e-17)); std::cout << std::format("1e-17 vs 0.0: {}\n", eps_equal(1e-17, 0.0)); // A classic bug: abs() without std:: can pick the C int abs(int), // which truncates 0.2 to 0 and makes every difference "zero" double a = 0.3, b = 0.1; std::cout << "abs(a - b) = " << abs(a - b) << '\n'; std::cout << "std::abs(a - b) = " << std::abs(a - b) << '\n'; }
Output
gap above 1.0: 2.220446049250313e-16 is exactly epsilon, so 0.1 + 0.2 vs 0.3: true passes. Around 300 the gap is 5.684341886080802e-14, 256 times bigger, and a sum that is off by one step fails: 100.1 + 200.2 vs 300.3: false. Near zero the opposite goes wrong: 1e-20 vs 1e-17: true although one is 1000 times the other. Multiplying epsilon by the magnitude, as in section 1, fixes both. The last two lines are a separate classic bug: a bare abs(a - b) called the C function int abs(int), which truncated 0.2 to 0, and GCC compiled it without a warning. Always write std::abs or std::fabs.
4Counting ULPs with std::bit_cast
A ULP (unit in the last place) is the gap between a double and its neighbour. Counting how many representable doubles lie between two values is a tolerance that scales itself: "within 4 ULPs" means four rounding steps apart at any magnitude. Test frameworks use it (GoogleTest's EXPECT_DOUBLE_EQ allows 4 ULPs). The trick: for doubles of the same sign, the bit patterns read as integers are in the same order as the values, and C++20's std::bit_cast reads them without undefined behaviour.
#include <bit> #include <cmath> #include <cstdint> #include <format> #include <iostream> #include <limits> #include <numbers> // Reinterpret the bits as an integer that grows in the same order as the // double: positive doubles already do, negative ones count down from the // sign bit, so mirror them below zero (-0.0 and 0.0 both become 0) std::int64_t ordered_bits(double x) { auto bits = std::bit_cast<std::int64_t>(x); return bits < 0 ? std::numeric_limits<std::int64_t>::min() - bits : bits; } // How many representable doubles apart a and b are std::uint64_t ulp_distance(double a, double b) { auto ia = static_cast<std::uint64_t>(ordered_bits(a)); auto ib = static_cast<std::uint64_t>(ordered_bits(b)); return ordered_bits(a) > ordered_bits(b) ? ia - ib : ib - ia; } bool within_ulps(double a, double b, std::uint64_t max_ulps = 4) { if (std::isnan(a) || std::isnan(b)) { return false; } return ulp_distance(a, b) <= max_ulps; } int main() { // nextafter steps to the neighbouring double: exactly 1 ULP away double next = std::nextafter(1.0, 2.0); std::cout << std::format("next after 1.0: {}\n", next); std::cout << std::format("ULPs 1.0 to next: {}\n", ulp_distance(1.0, next)); // Typical rounding errors are 1 ULP, at any magnitude std::cout << std::format("0.1 + 0.2 vs 0.3: {} ULP\n", ulp_distance(0.1 + 0.2, 0.3)); std::cout << std::format("100.1 + 200.2 vs 300.3: {} ULP\n", ulp_distance(100.1 + 200.2, 300.3)); std::cout << std::format("within 4 ULPs: {}\n", within_ulps(100.1 + 200.2, 300.3)); // Signs are handled: -0.0 and 0.0 are the same point std::cout << std::format("-0.0 vs 0.0: {} ULPs\n", ulp_distance(-0.0, 0.0)); // But near zero ULPs are useless: doubles are densest there, so a // tiny leftover such as sin(pi) is billions of billions of ULPs from 0 double s = std::sin(std::numbers::pi); std::cout << std::format("sin(pi) = {}\n", s); std::cout << std::format("sin(pi) vs 0.0: {} ULPs\n", ulp_distance(s, 0.0)); }
Output
std::nextafter(1.0, 2.0) is the next double, 1.0000000000000002, exactly 1 ULP away. Both rounding errors from earlier are 1 ULP, at 0.3 and at 300.3 alike, so within 4 ULPs: true works where the fixed epsilon failed. Mirroring the negative bit patterns makes -0.0 vs 0.0: 0 ULPs and lets the distance cross zero. The weak spot is zero itself: doubles are packed densely there, so sin(pi), which is 1.2246467991473532e-16 instead of 0, is 4368955796522032135 ULPs from 0.0. Results that should be zero still need an absolute tolerance. Before C++20, std::memcpy into an integer is the safe way to read the bits; a reinterpret_cast or a union is undefined behaviour in C++.
5Checking for NaN, infinity and -0.0
NaN (not a number) is what 0.0 / 0.0, std::sqrt(-1.0) and similar operations return. It compares unequal to everything, itself included, so x == NAN can never find one. Use std::isnan from <cmath>. Its neighbours std::isinf, std::isfinite and std::signbit cover the other special values.
#include <algorithm> #include <cmath> #include <format> #include <iostream> #include <limits> int main() { double nan = std::numeric_limits<double>::quiet_NaN(); double zero = 0.0; double computed = zero / zero; // 0/0 is NaN, not a crash // std::isnan is the check to use std::cout << std::format("isnan(nan): {}, isnan(0/0): {}\n", std::isnan(nan), std::isnan(computed)); // Every comparison with NaN is false, except != std::cout << std::format("nan == nan: {}\n", nan == nan); std::cout << std::format("nan != nan: {}\n", nan != nan); std::cout << std::format("nan < 1: {}, nan > 1: {}, nan == 1: {}\n", nan < 1.0, nan > 1.0, nan == 1.0); // So x != x is true only for NaN (the pre-C++11 trick) std::cout << std::format("x != x for nan: {}, for 1.0: {}\n", nan != nan, 1.0 != 1.0); // std::max is (a < b) ? b : a, so where the NaN sits changes the result; // std::fmax ignores a NaN argument std::cout << std::format("std::max(nan, 1.0) = {}\n", std::max(nan, 1.0)); std::cout << std::format("std::max(1.0, nan) = {}\n", std::max(1.0, nan)); std::cout << std::format("std::fmax(nan, 1.0) = {}\n", std::fmax(nan, 1.0)); // Infinity is a normal value for ==; isfinite rules out both inf and NaN double inf = 1.0 / zero; std::cout << std::format("1/0 = {}, isinf: {}, inf == inf: {}\n", inf, std::isinf(inf), inf == inf); std::cout << std::format("isfinite: 1.0 {}, inf {}, nan {}\n", std::isfinite(1.0), std::isfinite(inf), std::isfinite(nan)); // -0.0 equals 0.0; only signbit (or dividing by it) tells them apart std::cout << std::format("-0.0 == 0.0: {}, signbit(-0.0): {}, 1/-0.0 = {}\n", -0.0 == 0.0, std::signbit(-0.0), 1.0 / -zero); }
Output
std::isnan is true for both NaNs, and every comparison prints false except nan != nan: true. That makes x != x a working NaN test, but std::isnan says what it means. NaN also breaks functions built on <: std::max(nan, 1.0) returns nan while std::max(1.0, nan) returns 1, and std::fmax skips the NaN either way. Infinity behaves like a normal value (inf == inf: true); std::isfinite rejects both infinity and NaN in one call, which is the usual input check. -0.0 == 0.0 is true, and only std::signbit or a division (1/-0.0 = -inf) shows the sign. One warning: with GCC's -ffast-math (or -ffinite-math-only) the compiler assumes NaN never happens and may turn both std::isnan(x) and x != x into false.
6Ordering and sorting with NaN: <=> and std::strong_order
In C++20, a <=> b on doubles returns std::partial_ordering, whose fourth result, unordered, is what you get when a NaN is involved. That is also why std::sort with < must not see a NaN: the comparison stops being a strict weak ordering, which is undefined behaviour and can scramble the output or read out of bounds. Either remove NaNs first, or sort with std::strong_order, a total order over every double.
#include <algorithm> #include <cmath> #include <compare> #include <format> #include <iostream> #include <limits> #include <vector> void print(const char* label, const std::vector<double>& v) { std::cout << label << ':'; for (double x : v) { std::cout << std::format(" {}", x); } std::cout << '\n'; } int main() { double nan = std::numeric_limits<double>::quiet_NaN(); double zero = 0.0; // <=> on doubles gives std::partial_ordering: NaN is "unordered" std::cout << std::format("2.0 <=> 1.0 is greater: {}\n", (2.0 <=> 1.0) == std::partial_ordering::greater); std::cout << std::format("nan <=> 1.0 is unordered: {}\n", (nan <=> 1.0) == std::partial_ordering::unordered); // Sorting with < and a NaN inside is undefined behaviour: < is not a // strict weak ordering any more. Option 1: drop the NaNs first. std::vector<double> values{3.5, nan, 0.0, -2.0, -0.0, 1.0}; std::vector<double> clean = values; std::erase_if(clean, [](double x) { return std::isnan(x); }); std::ranges::stable_sort(clean); // stable: equal 0.0 and -0.0 keep their order print("without NaN", clean); // Option 2: std::strong_order is a total order over all doubles: // -0.0 sorts before 0.0, and a positive NaN after everything auto total_less = [](double a, double b) { return std::strong_order(a, b) < 0; }; std::ranges::sort(values, total_less); print("strong_order", values); // A NaN can be negative: on x86-64, 0.0 / 0.0 produces -nan, // which strong_order puts before everything std::vector<double> mixed{1.0, zero / zero, nan, -1.0}; std::ranges::sort(mixed, total_less); print("signed NaNs", mixed); }
Output
Without NaNs, a plain sort works: without NaN: -2 0 -0 1 3.5. The 0 and -0 compare equal, so they keep their input order only because the example uses stable_sort. std::strong_order orders everything, -0 before 0 and a NaN at the end: strong_order: -2 -0 0 1 3.5 nan. But NaNs carry a sign bit too, and on x86-64 the NaN that 0.0 / 0.0 produces is negative, so it prints as -nan and sorts first: signed NaNs: -nan -1 1 nan. If all NaNs must go last, partition them out with std::isnan instead of relying on their sign.
7Which should you use?
| Method | Verdict | Best for |
|---|---|---|
| fabs(a - b) <= max(rel * max(|a|, |b|), abs) | Default | Computed values at any scale, with an absolute floor near zero |
| a == b | Exact only | Exact values: small integers, copies, sentinel values |
| fabs(a - b) < epsilon() | Avoid | Only correct for values between 1 and 2 |
| ULP distance (std::bit_cast) | Specialist | Tight checks in tests of numeric code; useless near zero |
| std::isnan(x) | Use | Detecting NaN; std::isfinite also rejects infinity |
| std::strong_order(a, b) | C++20 | Sorting or keying values that may hold NaN or -0.0 |
Frequently asked questions
Why is 0.1 + 0.2 not equal to 0.3 in C++?
A double stores binary fractions, and 0.1, 0.2 and 0.3 have no exact binary form, so each is rounded to the nearest double. The rounded 0.1 plus the rounded 0.2 comes out as 0.30000000000000004, one step above the double nearest to 0.3. Default std::cout output rounds to 6 digits and prints both as 0.3; use std::setprecision(17) or std::format("{}", x) to see the difference. Compare with a tolerance instead of ==.
What epsilon should I use to compare doubles in C++?
Not std::numeric_limits<double>::epsilon() on its own: it is the gap between doubles near 1.0, too small for larger values and too big near zero. Use a relative tolerance scaled by the larger value, std::fabs(a - b) <= rel * std::max(std::fabs(a), std::fabs(b)), with rel around 1e-9 for double and 1e-5 for float, and add an absolute tolerance chosen from your units when results can be near zero. Long calculations accumulate more error, so loosen rel to match.
How do I check if a double is NaN in C++?
Call std::isnan(x) from <cmath>. x == NAN never works, because NaN compares unequal to everything, itself included; x != x is true only for NaN, but it says less about intent. Both checks can be optimised away under -ffast-math or -ffinite-math-only, which let the compiler assume there are no NaNs. Use std::isfinite(x) to reject NaN and infinity in one call.
How do I compare a float with a double?
Convert both to the same type first. f == 0.7 is false for float f = 0.7f, because f is widened to the double 0.699999988079071 and compared with the double nearest to 0.7. Compare with a float literal (f == 0.7f) or static_cast<float>(d), or compare with a tolerance suited to float precision, about 7 significant digits.
When is it safe to compare floating-point numbers with ==?
When every value involved is exact: whole numbers up to 2^53 in a double (2^24 in a float), fractions with a power-of-two denominator such as 0.5 or 0.25, values you copied without arithmetic, and sentinel values you assigned yourself, such as a 0.0 that marks "not set". Anything computed with division, decimal fractions or library functions such as std::sin needs a tolerance.
Why does abs(a - b) return 0 for doubles?
Without the std:: prefix, abs can resolve to the C function int abs(int), which converts the double to an int and drops the fraction, so abs(0.3 - 0.1) is 0 and every small difference looks like a match. GCC compiled that call on this page with no warning. Write std::abs(a - b) or std::fabs(a - b) with <cmath> included.