Skip to content
systemcoding.dev
Fundamentals

Compare Floating-Point Numbers Safely With Epsilons and ULPs

Compare floats in C with an absolute tolerance, a relative tolerance and a ULP distance, see where each fails, and combine them into one safe helper.

8 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the C, Python and Rust logos.

Two floating-point numbers that should be equal rarely are, as the post on 0.1 + 0.2 shows. A calculation that is exact on paper picks up rounding errors, and comparing the result with == gives false. The usual fix is to compare within a tolerance, but the obvious tolerance, a fixed small number, is wrong for a wide range of inputs. This post walks through three ways to compare: an absolute epsilon, a relative epsilon and a distance measured in units in the last place. It shows a worked example where each one fails, and ends with a helper that combines them. The code is C17 built with GCC 14 on x86-64, using double, and the program links with -lm for nextafter and fmax.

When exact equality is right

Exact == on floating-point values is correct in a few situations, and worth knowing so you do not tolerance everything. It works when both numbers are integers or dyadic fractions small enough to be exact, such as 3.0 and 0.5. It works when you compare a value with itself or with a sentinel you assigned, such as a stored default of -1.0. And it works when the algorithm guarantees bit-identical results, for instance the same operations in the same order. Everything that comes out of different calculations should be compared with a tolerance.

Approach one: an absolute epsilon

The simplest comparison asks whether the difference is smaller than a fixed amount.

The test is fabs(a - b) <= eps. It treats the numbers as points on a line and asks how far apart they are. It is a good choice when you know the scale of the values, such as coordinates in a map of a few kilometres, where an error of a millimetre is meaningless. It breaks when values are large or small compared with eps. At around 10 to the 10, the gap between neighbouring doubles is about 2 times 10 to the minus 6, so a tolerance of 10 to the minus 9 is smaller than the spacing and the test degrades into exact equality. At 10 to the minus 12, the same tolerance calls two values equal when one is double the other.

Approach two: a relative epsilon

The relative test compares the difference with the size of the numbers: fabs(a - b) <= eps * fmax(fabs(a), fabs(b)). The tolerance scales with the magnitude, so a relative epsilon of 10 to the minus 9 means the two values agree to about nine significant digits, whatever the exponent. This matches how floating point itself works, since its precision is relative. It breaks near zero. If one value is exactly 0.0 and the other is 10 to the minus 300, the relative difference is 100 percent, and the test says they are different, though both are effectively zero.

Approach three: units in the last place

A ULP is the gap between a float and the next one. Counting the number of representable values between two numbers gives a tolerance that is relative by construction and does not depend on picking an epsilon in decimal. Two adjacent doubles are 1 ULP apart. The trick that makes it cheap is that the bit patterns of IEEE 754 numbers, read as integers, are ordered like the numbers themselves for positive values, so the difference of the integer representations is the ULP distance. Negative values need a fix: their patterns are in sign and magnitude, so map them into a continuous integer order before subtracting.

ulp.cc
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

static int64_t ordered(double d)
{
    int64_t i;
    memcpy(&i, &d, sizeof i);
    return (i < 0) ? (int64_t)(INT64_MIN - i) : i;
}

static uint64_t ulp_diff(double a, double b)
{
    int64_t x = ordered(a);
    int64_t y = ordered(b);
    return (x > y) ? (uint64_t)x - (uint64_t)y : (uint64_t)y - (uint64_t)x;
}

int main(void)
{
    double next = nextafter(1.0, 2.0);
    double next2 = nextafter(next, 2.0);

    printf("0.1+0.2 vs 0.3   : %llu\n", (unsigned long long)ulp_diff(0.1 + 0.2, 0.3));
    printf("1.0 vs next      : %llu\n", (unsigned long long)ulp_diff(1.0, next));
    printf("1.0 vs next2     : %llu\n", (unsigned long long)ulp_diff(1.0, next2));
    printf("0.0 vs -0.0      : %llu\n", (unsigned long long)ulp_diff(0.0, -0.0));
    printf("1.0 vs 1.0+1e-9  : %llu\n", (unsigned long long)ulp_diff(1.0, 1.0 + 1e-9));
    printf("100.0 vs 100.1   : %llu\n", (unsigned long long)ulp_diff(100.0, 100.1));
    return 0;
}

The ordered function reinterprets the double as a signed 64-bit integer with memcpy. A negative double has the top bit set, so its integer reading is negative, and the expression INT64_MIN - i flips it into a position below zero in the right order: negative zero, which is INT64_MIN as an integer, maps to 0, the same as positive zero. The subtraction at the end is done in unsigned arithmetic, which cannot overflow.

Text
0.1+0.2 vs 0.3   : 1
1.0 vs next      : 1
1.0 vs next2     : 2
0.0 vs -0.0      : 0
1.0 vs 1.0+1e-9  : 4503600
100.0 vs 100.1   : 7036874417766

The first line confirms what the earlier post showed: the two values are neighbours. The two zeros are 0 ULP apart, which is right, since they compare equal. The last two lines show how large a ULP count becomes for differences that are visible to the eye: a billionth away from 1.0 is about 4.5 million ULPs. A tolerance of a few ULPs, such as 4, accepts the rounding noise of a short calculation and rejects real differences.

Two limits apply. The ULP measure is not meaningful across zero, for values of opposite sign that are tiny, since the integer order passes through the subnormals and the count is huge even for values that are close in absolute terms. And it treats NaN as unordered nonsense, so check isnan first.

Where each one fails: a worked comparison

The helpers below implement the absolute and relative tests, and the program runs four cases through both, so you can see which one gets each right.

compare.cc
#include <math.h>
#include <stdio.h>

static int abs_equal(double a, double b, double eps)
{
    return fabs(a - b) <= eps;
}

static int rel_equal(double a, double b, double eps)
{
    return fabs(a - b) <= eps * fmax(fabs(a), fabs(b));
}

int main(void)
{
    printf("A 0.1+0.2 vs 0.3:   abs=%d rel=%d\n",
           abs_equal(0.1 + 0.2, 0.3, 1e-9), rel_equal(0.1 + 0.2, 0.3, 1e-9));
    printf("B 1e10 vs 1e10+1:   abs=%d rel=%d\n",
           abs_equal(1e10, 1e10 + 1.0, 1e-9), rel_equal(1e10, 1e10 + 1.0, 1e-9));
    printf("C 1e-12 vs 2e-12:   abs=%d rel=%d\n",
           abs_equal(1e-12, 2e-12, 1e-9), rel_equal(1e-12, 2e-12, 1e-9));
    printf("D 0 vs 1e-300:      abs=%d rel=%d\n",
           abs_equal(0.0, 1e-300, 1e-9), rel_equal(0.0, 1e-300, 1e-9));
    return 0;
}

Case A is the familiar rounding noise, and both tests accept it. Case B compares two large numbers that differ by 1, which is a relative difference of 10 to the minus 10: the absolute test rejects it, since the difference is far above 10 to the minus 9, while the relative test accepts. Case C compares two tiny numbers that differ by a factor of two. The absolute test calls them equal because both are below the tolerance, which is almost certainly wrong, and the relative test correctly says no. Case D compares zero with a value near the smallest doubles: the relative test says no, since the ratio is infinite, while the absolute test says yes.

Text
A 0.1+0.2 vs 0.3:   abs=1 rel=1
B 1e10 vs 1e10+1:   abs=0 rel=1
C 1e-12 vs 2e-12:   abs=1 rel=0
D 0 vs 1e-300:      abs=1 rel=0

Neither test is right on all four, which is the whole point. The absolute test is right for values near zero and wrong for large ones. The relative test is right for large values and wrong near zero.

A combined helper

The standard solution applies both: the numbers are equal if they are within a small absolute tolerance, which handles values near zero, or within a relative tolerance, which handles everything else.

approx.cc
#include <math.h>
#include <stdio.h>

static int approx_equal(double a, double b, double abs_eps, double rel_eps)
{
    if (isnan(a) || isnan(b)) {
        return 0;
    }
    if (a == b) {
        return 1;
    }
    double diff = fabs(a - b);
    if (diff <= abs_eps) {
        return 1;
    }
    return diff <= rel_eps * fmax(fabs(a), fabs(b));
}

int main(void)
{
    printf("%d\n", approx_equal(0.1 + 0.2, 0.3, 1e-12, 1e-9));
    printf("%d\n", approx_equal(1e10, 1e10 + 1.0, 1e-12, 1e-9));
    printf("%d\n", approx_equal(1.0, 1.0001, 1e-12, 1e-9));
    printf("%d\n", approx_equal(NAN, NAN, 1e-12, 1e-9));
    printf("%d\n", approx_equal(INFINITY, INFINITY, 1e-12, 1e-9));
    return 0;
}

The early a == b handles equal infinities, since INFINITY - INFINITY would be NaN. The NaN check returns false for any NaN, matching the usual rule that NaN is equal to nothing. A difference of 0.0001 between 1.0 and 1.0001 is much larger than both tolerances, so the third call is false.

Text
1
1
0
0
1

Choosing the tolerances

There is no universal epsilon. Pick the relative tolerance from the precision you need and the error your calculation can accumulate. For double, a relative tolerance of 10 to the minus 9 accepts agreement to nine digits, far above the 10 to the minus 16 of a single operation, which leaves room for thousands of operations. For float, use about 10 to the minus 5. Choose the absolute tolerance from the scale at which values stop mattering in your problem, such as 10 to the minus 12 for quantities of order one. Do not use DBL_EPSILON directly as the tolerance: it is the spacing at 1.0, so it is too small for values above 1 and too large for values below.

For tests, many frameworks provide the comparison: GoogleTest has EXPECT_NEAR and EXPECT_DOUBLE_EQ, which allows 4 ULPs, and Python has math.isclose with both tolerances. Use them where they exist, and write the helper above for plain C.

Common mistakes

  • Using DBL_EPSILON as a universal tolerance.

  • Using only an absolute tolerance on values that span many orders of magnitude.

  • Using only a relative tolerance when one value can be zero.

  • Comparing with ULPs across the sign boundary or with NaN.

  • Accepting a tolerance so loose that real bugs pass, which defeats the test.

Taggedcbeginner
Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.