Skip to content
systemcoding.dev
Fundamentals

The Complete Guide to IEEE 754 Floating Point for Systems Programmers

A complete guide to IEEE 754 floating point: formats, encoding, rounding, error, exceptions, FMA and compiler flags, with C code and exact output.

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

Floating point is the one numeric type that behaves differently from the arithmetic you learned at school, and it behaves the same way on nearly every machine you will ever touch. The reason is a single standard, IEEE 754, published in 1985 and revised in 2008 and 2019, which fixed the layout of the bits, the rounding of every basic operation, the special values and the exception flags. Once you know the standard, the oddities stop being mysterious: 0.1 + 0.2 is not 0.3 for a reason you can compute by hand, a loop that adds 0.1 ten times does not reach 1, and one compiler flag can quietly delete your NaN checks. This guide is for programmers who work close to the machine and want a precise model. It covers the formats, the encoding of normal, subnormal and special values, spacing and units in the last place, rounding, converting between decimal and binary, how errors grow through addition, cancellation and summation, fused multiply-add, the exception flags in fenv.h, conversions between integers and floats, and the compiler options that change the results. Every section has C code with its exact output, written for GCC 14 on x86-64 Linux with glibc 2.40 and SSE2 arithmetic, linked with -lm, and each points to a focused post. It builds on the guides to bits and to integers.

The formats

IEEE 754 defines several binary formats. All share one design: a sign bit, an exponent field with a bias, and a fraction field, and the bit widths differ. The standard calls them binary16, binary32, binary64 and binary128, and C's float and double are binary32 and binary64 on every mainstream platform.

FormatCommon nameSignExponentFractionSignificand bitsExponent bias
binary16half15101115
bfloat16brain float1878127
binary32single, float182324127
binary64double, double11152531,023
binary128quad11511211316,383

The significand has one more bit than the stored fraction, because the leading 1 of a normal number is implied. Bfloat16 is not an IEEE format, but it appears constantly in machine learning hardware: it keeps the 8-bit exponent of float, and so the same range, and gives up precision by cutting the fraction to 7 bits. The 80-bit extended format of the x87 unit, with a 64-bit significand, is an IEEE extended format, and it is what long double is on x86 Linux.

The numbers that follow from the layouts are the limits you will meet.

FormatLargest finiteSmallest normalGap between 1.0 and the next value
binary1665,5042 to the minus 14, about 6.1 times 10 to the minus 52 to the minus 10, about 0.00098
bfloat16about 3.4 times 10 to the 382 to the minus 1262 to the minus 7, 0.0078125
binary32about 3.4 times 10 to the 38about 1.18 times 10 to the minus 382 to the minus 23, about 1.19 times 10 to the minus 7
binary64about 1.8 times 10 to the 308about 2.2 times 10 to the minus 3082 to the minus 52, about 2.22 times 10 to the minus 16
binary128about 1.2 times 10 to the 4,932about 3.4 times 10 to the minus 4,9322 to the minus 112, about 1.9 times 10 to the minus 34

The gap in the last column is the machine epsilon, exposed in C as FLT_EPSILON and DBL_EPSILON. It is the unit of precision at the value 1. The post on how floating-point numbers are stored derives the layout of float field by field, and the post on float against double compares the two on range, memory and speed. The rest of this guide uses double, and everything applies to the other formats with different widths.

How a value is encoded

A 64-bit double is read as three fields from the top: one sign bit s, eleven exponent bits e and fifty-two fraction bits f. What the fields mean depends on the exponent.

Exponent fieldFractionMeaningValue
all zeroszerozeroplus or minus 0
all zerosnon-zerosubnormal(-1)^s times 0.f times 2 to the minus 1,022
1 to 2,046anynormal(-1)^s times 1.f times 2 to the (e minus 1,023)
all oneszeroinfinityplus or minus infinity
all onesnon-zeroNaNnot a number

A normal number has an implied leading 1 and the stored exponent minus the bias as its power of two. A subnormal number has a zero exponent field, no implied 1 and a fixed exponent equal to that of the smallest normal number, so it fills the gap between zero and the smallest normal in evenly spaced steps. This is called gradual underflow, and it means that the difference of two distinct floats is never zero: if x != y, then x - y != 0, which is a property that code can rely on. Without subnormals there would be a wide hole around zero and that property would fail.

The program below reads a double's bits through memcpy, splits the three fields and classifies the value with fpclassify, for eight representative values.

decode.cc
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

static const char *kind(double d)
{
    switch (fpclassify(d)) {
    case FP_NAN:       return "FP_NAN";
    case FP_INFINITE:  return "FP_INFINITE";
    case FP_ZERO:      return "FP_ZERO";
    case FP_SUBNORMAL: return "FP_SUBNORMAL";
    default:           return "FP_NORMAL";
    }
}

static void decode(const char *name, double d)
{
    uint64_t u;
    memcpy(&u, &d, sizeof u);
    printf("%-8s 0x%016" PRIX64 "  s=%u e=0x%03X f=0x%013" PRIX64 "  %s\n",
           name, u, (unsigned)(u >> 63), (unsigned)((u >> 52) & 0x7FFu),
           u & 0xFFFFFFFFFFFFFULL, kind(d));
}

int main(void)
{
    decode("1.0", 1.0);
    decode("0.1", 0.1);
    decode("-0.0", -0.0);
    decode("5e-324", DBL_TRUE_MIN);
    decode("DBL_MIN", DBL_MIN);
    decode("DBL_MAX", DBL_MAX);
    decode("+inf", INFINITY);
    decode("NaN", NAN);
    return 0;
}

The mask 0xFFFFFFFFFFFFF has thirteen hex digits, which is the 52 fraction bits, and %013 pads the fraction to the same width. The bit patterns encode the table directly.

Text
1.0      0x3FF0000000000000  s=0 e=0x3FF f=0x0000000000000  FP_NORMAL
0.1      0x3FB999999999999A  s=0 e=0x3FB f=0x999999999999A  FP_NORMAL
-0.0     0x8000000000000000  s=1 e=0x000 f=0x0000000000000  FP_ZERO
5e-324   0x0000000000000001  s=0 e=0x000 f=0x0000000000001  FP_SUBNORMAL
DBL_MIN  0x0010000000000000  s=0 e=0x001 f=0x0000000000000  FP_NORMAL
DBL_MAX  0x7FEFFFFFFFFFFFFF  s=0 e=0x7FE f=0xFFFFFFFFFFFFF  FP_NORMAL
+inf     0x7FF0000000000000  s=0 e=0x7FF f=0x0000000000000  FP_INFINITE
NaN      0x7FF8000000000000  s=0 e=0x7FF f=0x8000000000000  FP_NAN

Read them as the table says. The value 1.0 has exponent 0x3FF, which is 1,023, the bias, so the true exponent is 0, and a zero fraction. The value 0.1 has exponent 0x3FB, which is 1,019, so the true exponent is minus 4, and the repeating 9 digits in the fraction are the binary expansion of one tenth rounded to 52 bits. The smallest positive double, DBL_TRUE_MIN, is the pattern with only the lowest fraction bit set, 2 to the minus 1,074, about 4.94 times 10 to the minus 324. DBL_MIN is the smallest normal, 2 to the minus 1,022. DBL_MAX has the largest finite exponent and an all-ones fraction. Infinity and NaN share the all-ones exponent, and the NaN produced by the NAN macro is a quiet NaN, with the top fraction bit set.

The post on NaN, infinity and negative zero covers the special values in detail, including how to test for them and why -ffast-math removes the tests.

Spacing, ULPs and relative error

Floats are not evenly spaced. Within each interval from 2 to the n up to 2 to the n plus 1, there are the same number of values, 2 to the 52 for a double, spread evenly, so the gap between neighbours doubles every time the exponent goes up by one. The gap between a float and the next larger one is its unit in the last place, or ULP. For a normal double x, the ULP is 2 to the (exponent of x) minus 52.

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

int main(void)
{
    const double xs[] = { 1.0, 1024.0, 1e10, 9007199254740992.0 };

    for (int i = 0; i < 4; i++) {
        double gap = nextafter(xs[i], INFINITY) - xs[i];
        printf("spacing at %-20.17g = %g\n", xs[i], gap);
    }
    return 0;
}

The function nextafter returns the neighbouring double in the stated direction, so the difference is the ULP at that value.

Text
spacing at 1                    = 2.22045e-16
spacing at 1024                 = 2.27374e-13
spacing at 10000000000          = 1.90735e-06
spacing at 9007199254740992     = 2

At 1.0 the gap is DBL_EPSILON. At 1,024, which is 2 to the 10, it is 2 to the minus 42. At ten billion, near 2 to the 33, it is 2 to the minus 19, about two millionths. At 2 to the 53, the gap is 2, which is why the integer 9,007,199,254,740,993 cannot be stored: the doubles at that scale are all even. A double represents every integer up to 2 to the 53 exactly, and the same fact for float is 2 to the 24, which is 16,777,216.

The important consequence is that the relative spacing is almost constant. The ULP divided by the value lies between 2 to the minus 53 and 2 to the minus 52, about 1.1 times 10 to the minus 16 to 2.2 times 10 to the minus 16, throughout the range. A double therefore has about sixteen significant decimal digits whether the value is a nanometre or a light-year. This is the right model for most science and engineering, and the wrong one for exact decimal quantities such as money, where the absolute error matters.

Rounding

An operation on two floats generally has a result that is not itself a float. IEEE 754 requires that addition, subtraction, multiplication, division and square root be correctly rounded: the result must be the same as if the exact mathematical answer were computed with unlimited precision and then rounded once to the destination format. The default rounding rule is round to nearest, ties to even. The exact result is replaced by the nearest representable value, and when it lies exactly halfway between two, by the one whose last significand bit is zero. The tie rule has no bias: over many operations, ties round up as often as down.

Correct rounding gives a clean bound on error. For any basic operation whose exact result lies within the normal range, the computed result differs from the exact one by at most half a ULP, which is a relative error of at most 2 to the minus 53 for a double. That number, called the unit roundoff u, is the basis of every error analysis. Each operation is exact up to a factor of 1 + d with d no larger than u in magnitude. A computation of a hundred operations can be off by about a hundred times u in the worst case, and typically by far less because errors partly cancel.

The standard defines four other rounding modes, round toward positive infinity, toward negative infinity, toward zero, and ties away from zero in the decimal formats, and C exposes the first three through fesetround in fenv.h. They are used by interval arithmetic and by careful numerical code to bound a result from both sides, and are rarely changed in ordinary programs. The post on IEEE 754 rounding modes and fesetround covers them.

Rounding is why 0.1 is not 0.1. The decimal fraction one tenth has an infinite binary expansion, so it is rounded to the nearest double, which is slightly larger than 0.1. The next section shows the effect on printing, and the post on why 0.1 + 0.2 does not equal 0.3 works through the arithmetic.

Converting between decimal and binary

A decimal string read into a double is rounded to the nearest representable value, and strtod and the compiler both do this correctly. A double printed back in decimal can use as many digits as you ask for, and the question is how many are enough. Seventeen significant digits always suffice to identify any double uniquely, so printing with %.17g and reading the result back recovers the original bits. Fifteen digits is the most that survives a trip in the other direction: any decimal string of up to 15 significant digits converts to a double and back to the same string. Those two figures are DBL_DECIMAL_DIG, which is 17, and DBL_DIG, which is 15.

Often fewer than 17 digits suffice for a particular value, and the shortest string that reads back as the same double is the most useful one to print, since it is the least noisy and still exact. Many languages print this form by default. In C you find it by trying increasing precisions until the round trip works.

shortest.cc
#include <float.h>
#include <stdio.h>
#include <stdlib.h>

static int shortest(double v, char *buf, size_t n)
{
    for (int p = 1; p <= 17; p++) {
        snprintf(buf, n, "%.*g", p, v);
        if (strtod(buf, NULL) == v) {
            return p;
        }
    }
    return 17;
}

int main(void)
{
    struct { const char *label; double value; } items[] = {
        { "0.1", 0.1 },
        { "0.1 + 0.2", 0.1 + 0.2 },
        { "1.0 / 3.0", 1.0 / 3.0 },
        { "1e23", 1e23 },
        { "DBL_TRUE_MIN", DBL_TRUE_MIN },
    };
    char text[40];

    for (size_t i = 0; i < sizeof items / sizeof items[0]; i++) {
        int p = shortest(items[i].value, text, sizeof text);
        printf("%-14s %2d digits: %s\n", items[i].label, p, text);
    }
    return 0;
}

Each trial formats the value with p significant digits and parses the text again. The first precision at which the parsed value equals the original is the length of the shortest representation.

Text
0.1             1 digits: 0.1
0.1 + 0.2      17 digits: 0.30000000000000004
1.0 / 3.0      16 digits: 0.3333333333333333
1e23            1 digits: 1e+23
DBL_TRUE_MIN    1 digits: 5e-324

The first line shows that the stored value nearest 0.1 reads back as 0.1 from a single digit, even though its exact decimal expansion is 0.1000000000000000055511151231257827. The second needs all 17, and that is the visible mark of the rounding error in the sum. The third needs 16. The hexadecimal float format, %a, prints the exact binary value with no rounding, which is the way to see what is really stored, and is accepted by strtod and by C source as a literal. A newer algorithm family such as Ryu and the one in C++17's to_chars computes the shortest string directly, without the trial loop.

How errors grow

A single operation is accurate to half a ULP. The trouble in real programs comes from how errors combine, and four patterns account for most of it.

Absorption. Adding a small number to a large one loses the small one's low digits, because the sum is rounded to the large number's precision. If the small number is below half a ULP of the large one, the sum equals the large one and the small number vanishes. Non-associativity. Because every addition rounds, (a + b) + c and a + (b + c) can differ, so the order of a sum changes its value. Cancellation. Subtracting two nearly equal numbers cancels their leading digits and leaves the noise in the trailing digits, which was a small relative error and is now a large one. The subtraction itself is exact, and the damage was done earlier, in the rounding of the operands.

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

int main(void)
{
    volatile double big = 1e16;
    volatile double one = 1.0;
    volatile double x = 1e-8;

    printf("1e16 + 1 == 1e16: %d\n", big + one == big);
    printf("(1e16 + 1) + 1 = %.17g\n", (big + one) + one);
    printf("1e16 + (1 + 1) = %.17g\n", big + (one + one));

    double naive = 1.0 - cos(x);
    double stable = 2.0 * sin(x / 2.0) * sin(x / 2.0);
    printf("naive  1 - cos(x)    = %g\n", naive);
    printf("stable 2 sin^2(x/2)  = %g\n", stable);
    return 0;
}

The volatile qualifiers stop the compiler from folding the constants. At 1e16 the ULP is 2, so adding 1 lands exactly halfway between two doubles and rounds to the even neighbour, which is 1e16 itself: the 1 is absorbed, twice in a row. Adding the 1s together first gives 2, which is a full ULP and survives. For the second pair, cos(1e-8) is 1 minus 5 times 10 to the minus 17, which is closer to 1.0 than to the next double below it, so it rounds to exactly 1.0 and the naive difference is zero. The trigonometric identity 1 - cos(x) = 2 sin squared of x over 2 avoids the subtraction and keeps full accuracy.

Text
1e16 + 1 == 1e16: 1
(1e16 + 1) + 1 = 10000000000000000
1e16 + (1 + 1) = 10000000000000002
naive  1 - cos(x)    = 0
stable 2 sin^2(x/2)  = 5e-17

The correct answer is about 5 times 10 to the minus 17, so the naive form has lost every significant digit. This pattern, rewriting a formula to avoid subtracting nearly equal values, is the core skill of numerical programming. Another familiar case is the quadratic formula, where one root involves -b + sqrt(b*b - 4*a*c) and cancels when b is large, and the standard fix computes the other root first and uses the product of the roots.

Summing many numbers

A sum of many terms accumulates absorption errors that grow with the number of terms. Compensated summation, due to Kahan, keeps a running correction term that captures the low-order bits lost at each step and feeds them back into the next addition. The cost is a few extra operations per term, and the error no longer grows with the length of the sum.

kahan.cc
#include <stdio.h>

static double kahan_sum(const double *x, int n)
{
    double sum = 0.0;
    double c = 0.0;

    for (int i = 0; i < n; i++) {
        double y = x[i] - c;
        double t = sum + y;
        c = (t - sum) - y;
        sum = t;
    }
    return sum;
}

int main(void)
{
    double terms[10];
    double naive = 0.0;

    for (int i = 0; i < 10; i++) {
        terms[i] = 0.1;
        naive += terms[i];
    }
    printf("naive sum = %.17g\n", naive);
    printf("Kahan sum = %.17g\n", kahan_sum(terms, 10));
    return 0;
}

The correction c is algebraically zero, and in floating point it holds exactly the rounding error of the last addition. The algorithm only works if the compiler leaves the expression alone, and -ffast-math allows it to simplify (t - sum) - y to zero, which turns Kahan summation back into the plain loop.

Text
naive sum = 0.99999999999999989
Kahan sum = 1

The compensated sum reaches exactly 1 where the naive one falls one ULP short. Pairwise summation, which adds halves recursively, has error growth of the logarithm of the length, with no extra state, and is what many libraries use. Another simple improvement is to sort by magnitude and add the smallest first. Accumulating in a wider type, such as a double accumulator over float data, is the cheapest fix of all.

Fused multiply-add

Many processors have an instruction that computes a * b + c with one rounding instead of two. The C function fma does it, and hardware with FMA support does it in a single instruction. The extra accuracy is real, and it matters for polynomial evaluation, dot products and the error-free transformations that compensated algorithms use. It also makes results differ between machines and compilers: if the compiler contracts a * b + c into an FMA on one target and not on another, the last bit of the result changes.

fma.cc
#include <float.h>
#include <math.h>
#include <stdio.h>

int main(void)
{
    volatile double e = DBL_EPSILON;
    double a = 1.0 + e;
    double c = 1.0 + 2.0 * e;

    printf("a * a - c       = %g\n", a * a - c);
    printf("fma(a, a, -c)   = %g\n", fma(a, a, -c));
    return 0;
}

The exact square of 1 + e is 1 + 2e + e squared. The rounded product keeps 1 + 2e and discards the tiny e squared, which is 2 to the minus 104, so the ordinary expression gives zero. The fused version computes the exact product, subtracts c and rounds once, so it recovers the term that was lost. For the output to be deterministic, build with -ffp-contract=off, otherwise GCC on a target with FMA is allowed to fuse the first expression too.

Text
a * a - c       = 0
fma(a, a, -c)   = 4.93038e-32

GCC's default is -ffp-contract=fast in GNU C mode, which permits fusing across statements, and -ffp-contract=off in strict ISO mode. For reproducible numerical results across machines, turn contraction off and compare outputs.

Exceptions and status flags

IEEE 754 defines five exceptional conditions. Each raises a sticky flag, which stays set until cleared, and by default execution continues with a defined result, so no signal is raised.

Flag in fenv.hConditionDefault result
FE_INVALIDan operation with no defined result, such as 0/0 or sqrt(-1)NaN
FE_DIVBYZEROa finite non-zero number divided by zeroinfinity with the right sign
FE_OVERFLOWa result too large for the formatinfinity, or the largest finite value in some rounding modes
FE_UNDERFLOWa tiny result that is also inexacta subnormal or zero
FE_INEXACTthe rounded result differs from the exact onethe rounded result

C gives access through feclearexcept, fetestexcept and feraiseexcept, with the flags as bit masks. The program below runs six operations, clears the flags between them and prints which were raised. The operands are volatile to defeat constant folding, and the code should be compiled with -O0 or -O1, since GCC does not honour #pragma STDC FENV_ACCESS and may reorder flag-setting operations at higher levels.

flags.cc
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.h>

static void report(const char *what)
{
    printf("%-22s divbyzero=%d invalid=%d overflow=%d underflow=%d inexact=%d\n",
           what,
           !!fetestexcept(FE_DIVBYZERO), !!fetestexcept(FE_INVALID),
           !!fetestexcept(FE_OVERFLOW), !!fetestexcept(FE_UNDERFLOW),
           !!fetestexcept(FE_INEXACT));
    feclearexcept(FE_ALL_EXCEPT);
}

int main(void)
{
    volatile double zero = 0.0, one = 1.0, minus = -1.0, three = 3.0;
    volatile double big = DBL_MAX, tiny = DBL_MIN;
    volatile double r;

    feclearexcept(FE_ALL_EXCEPT);
    r = one / zero;    report("1.0 / 0.0");
    r = sqrt(minus);   report("sqrt(-1.0)");
    r = big * 2.0;     report("DBL_MAX * 2.0");
    r = tiny / three;  report("DBL_MIN / 3.0");
    r = one / three;   report("1.0 / 3.0");
    r = one + one;     report("1.0 + 1.0");
    (void)r;
    return 0;
}

Each line shows a different mix. Division by a zero raises only the divide-by-zero flag. The square root of a negative number raises invalid. The overflow case also raises inexact, since an overflowed result is by definition not exact. The last-but-one cases show underflow and the ubiquitous inexact flag, which is raised by almost every real computation.

Text
1.0 / 0.0              divbyzero=1 invalid=0 overflow=0 underflow=0 inexact=0
sqrt(-1.0)             divbyzero=0 invalid=1 overflow=0 underflow=0 inexact=0
DBL_MAX * 2.0          divbyzero=0 invalid=0 overflow=1 underflow=0 inexact=1
DBL_MIN / 3.0          divbyzero=0 invalid=0 overflow=0 underflow=1 inexact=1
1.0 / 3.0              divbyzero=0 invalid=0 overflow=0 underflow=0 inexact=1
1.0 + 1.0              divbyzero=0 invalid=0 overflow=0 underflow=0 inexact=0

The flags are a cheap way to check a long computation: clear them at the start, run, and test FE_INVALID, FE_DIVBYZERO and FE_OVERFLOW at the end. A raised invalid flag with no NaN in the output means a NaN was produced and later discarded by a comparison or a fmax. With glibc on Linux you can also turn the flags into signals using feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW), which delivers SIGFPE at the faulting instruction, so a debugger shows where the first NaN or infinity was created. That is often the quickest way to find the source of a NaN.

Converting between integers and floats

Conversions between integer and floating-point types are common and not always exact. An integer converts to a float by rounding to the nearest representable value, so every integer of magnitude up to 2 to the 24 is exact in a float and up to 2 to the 53 in a double, and above that some are not. A 64-bit integer can lose low bits when it becomes a double, and the largest one, INT64_MAX, rounds up to 2 to the 63 exactly.

The other direction is the dangerous one. A float converted to an integer type is truncated toward zero, and if the truncated value does not fit in the target type, the behaviour is undefined. That includes NaN and infinity. On x86-64 the hardware conversion instruction returns a special "integer indefinite" value, the minimum of the type, for any out-of-range input, but a compiler that sees the undefined behaviour may do something else entirely. Code that converts floats from an untrusted or computed source must range-check first.

convert.cc
#include <math.h>
#include <stdint.h>
#include <stdio.h>

static int32_t sat_to_i32(double x)
{
    if (x != x) {
        return 0;
    }
    if (x >= 2147483648.0) {
        return INT32_MAX;
    }
    if (x <= -2147483649.0) {
        return INT32_MIN;
    }
    return (int32_t)x;
}

int main(void)
{
    volatile int64_t odd = 9007199254740993LL;
    volatile int32_t n = 16777217;

    printf("(double)(2^53 + 1)   = %.0f\n", (double)odd);
    printf("(float)(2^24 + 1)    = %.0f\n", (double)(float)n);
    printf("(double)INT64_MAX    = %.0f\n", (double)INT64_MAX);
    printf("sat_to_i32(3.99)     = %d\n", sat_to_i32(3.99));
    printf("sat_to_i32(-3.99)    = %d\n", sat_to_i32(-3.99));
    printf("sat_to_i32(3e10)     = %d\n", sat_to_i32(3e10));
    printf("sat_to_i32(-3e10)    = %d\n", sat_to_i32(-3e10));
    printf("sat_to_i32(NAN)      = %d\n", sat_to_i32(NAN));
    return 0;
}

The helper makes each case explicit: NaN becomes zero, values at or beyond the limits saturate, and everything else truncates, which is defined because it fits. The bounds are written as exact doubles: 2,147,483,648 and minus 2,147,483,649 are both representable, and the truncation of anything in between lands inside the int32_t range.

Text
(double)(2^53 + 1)   = 9007199254740992
(float)(2^24 + 1)    = 16777216
(double)INT64_MAX    = 9223372036854775808
sat_to_i32(3.99)     = 3
sat_to_i32(-3.99)    = -3
sat_to_i32(3e10)     = 2147483647
sat_to_i32(-3e10)    = -2147483648
sat_to_i32(NAN)      = 0

The first two lines are the exactness limits, shown with the odd integers just above them. The third shows that the largest 64-bit integer, 9,223,372,036,854,775,807, is not representable and becomes 2 to the 63. To convert a float to the nearest integer, and not toward zero, use lround, llround or nearbyint instead of a cast, and note that those functions also have an undefined result for values out of range, which they signal by raising FE_INVALID.

Evaluation order, precision and the compiler

The standard fixes the result of each operation but leaves the compiler room in how a whole expression is evaluated, and that is the source of most differences between machines and builds.

Extended precision. On 32-bit x86 using the x87 unit, intermediate results are held in 80-bit registers with a 64-bit significand, and are rounded to 53 bits only when stored to memory. A computation can then give a different answer depending on whether the compiler spilled a value. C reports the evaluation scheme in FLT_EVAL_METHOD from float.h: 0 means each operation is evaluated in its own type, which is what x86-64 with SSE2 and Arm do, and 2 means operations are evaluated in long double, which is what the x87 does. The post on 0.1 + 0.2 shows a case where the answer depends on the format used.

Contraction. As noted above, -ffp-contract controls whether a * b + c may be fused. GCC's default in GNU C mode permits it on targets that have the instruction. Build with -ffp-contract=off if bit-for-bit reproducibility across targets matters.

Fast-math. The option -ffast-math is shorthand for several assumptions at once, including -ffinite-math-only, which says no NaN or infinity ever occurs, -fassociative-math, which lets the compiler reorder sums and products, -fno-signed-zeros, which treats the two zeros as equal, and -freciprocal-math, which allows division to be replaced by multiplication by a reciprocal. Each is a licence to produce faster code that breaks one of the properties in this guide. With fast-math on, isnan(x) may be folded to false, Kahan summation may be simplified to the naive loop, and a function that is correct under IEEE rules can return NaN or garbage. Use the individual flags that your code actually tolerates, such as -fno-math-errno, which only stops sqrt from setting errno and is nearly always safe, and keep the code that depends on special values in a file built without the others.

Flushing subnormals. Many processors handle subnormal values slowly, and some have modes that treat them as zero. On x86 with SSE, the flags are flush-to-zero and denormals-are-zero in the MXCSR register, and GCC with -ffast-math links in start-up code that sets them. With the modes on, x - y can be zero for unequal x and y, the guarantee that gradual underflow gives is lost, and results change. Audio and graphics code often turns them on deliberately for speed, and accepts the loss.

Library functions. The standard requires correct rounding only for the basic operations and sqrt. Functions such as sin, exp and pow are allowed an error of a few ULPs, and different libraries give slightly different results in the last digit. Two machines with identical hardware and different C libraries can disagree in the last place of a sin. If you need identical output across platforms, bundle your own implementation of the functions you use.

Comparing floats

Because results carry rounding error, the result of a calculation should rarely be compared with ==. Compare with a tolerance that fits the problem: an absolute tolerance for values near a known scale, a relative one for values of any magnitude, a combination of both to cover zero, or a ULP distance, computed by mapping the bit patterns onto a continuous integer line. The post on comparing floating-point numbers with epsilons and ULPs gives a helper and shows where each choice fails. Exact equality is right for values that are exactly representable and produced by exact operations, such as small integers stored in a double, and for sentinel values you assigned yourself.

Also remember what NaN does to ordering. Every comparison with a NaN is false except !=, so a sort, a binary search or a hash table keyed on floats misbehaves when a NaN is present. Filter NaNs first, or use a comparison that defines an order for them, such as the total order that IEEE 754-2019 specifies and Rust exposes as total_cmp.

Choosing a format

The practical guidance is short, and the post on float against double gives a decision table. Use double by default, since its 53 bits absorb most rounding error and it is as fast as float for scalar code on modern desktop processors. Use float when memory or bandwidth dominates, when the data is large, when SIMD lane count matters, or when the hardware has only a single-precision unit. Use long double or __float128 only when you have measured a need, since they are slower and their meaning varies by platform, and a compensated algorithm in double often gives the accuracy you wanted at less cost. Do not use binary floating point for money or for any quantity that must be exact in decimal: use integers of the smallest unit, or a decimal type.

For machine learning, the half-precision binary16 and bfloat16 formats trade precision for throughput and memory. Their 11-bit and 8-bit significands are far too coarse for general computation, so they are used for storage and matrix multiplication with a wider accumulator, a pattern that mirrors the advice about summing float data in a double.

Debugging numerical problems

When a program gives a wrong number, a short procedure finds the cause more reliably than staring at the code.

  1. Print enough digits. Use %.17g for doubles and %.9g for floats, so you see the stored value and not a rounded one, and use %a to see the exact bits.

  2. Check the flags. Clear the exception flags before a section, then test FE_INVALID, FE_DIVBYZERO and FE_OVERFLOW after it. A raised flag with no visible NaN means a special value appeared and was lost.

  3. Trap the first bad value. On glibc, feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW) turns the flags into SIGFPE at the faulting instruction, and a debugger then shows the line that created the first NaN or infinity.

  4. Vary the precision. Rerun with long double or with the data in a wider type. If the result moves a lot, the computation is ill-conditioned or loses digits to cancellation, and the fix is algebraic, not a different type.

  5. Vary the compiler. Rebuild with -O0, with -ffp-contract=off and without any fast-math flags. A result that depends on these has an ordering or fusion sensitivity that deserves a comment.

  6. Check for subnormals. If the program is unexpectedly slow, a stream of subnormal values may be the cause, and flushing them to zero is a measurable change.

  7. Compare against an exact reference. For a small case, compute the answer with integers or rationals, or with an arbitrary-precision library, and compare digit by digit.

A review checklist

When you read floating-point code, ask these questions in order.

  1. Is the format right: float or double, and are the literals and library functions of the matching type?

  2. Is any value compared with == after arithmetic? Is a tolerance appropriate?

  3. Is there a subtraction of nearly equal values that could be rewritten?

  4. Is a long sum accumulated in a narrower type than necessary, or in an order that absorbs small terms?

  5. Can a NaN or infinity reach the code, and what does each branch do with it? Is fast-math enabled anywhere?

  6. Is a float converted to an integer without a range check?

  7. Does the result need to be identical across machines, and if so, are contraction, library functions and extended precision controlled?

  8. Does the code use floats for a quantity that must be exact in decimal?

  9. Is the printed output enough digits to recover the value, and is the parsed input read with strtod, not atof?

Exercises

Work these by hand, then check with a program.

  1. What are the fields of the float 1.0, written in hex? The answer is 0x3F800000: sign 0, exponent 127, fraction 0.

  2. How many significant decimal digits can a double always round-trip through text? The answer is 15, and 17 are needed to recover a double from text.

  3. Why is 1e16 + 1 == 1e16 in double precision? The spacing at 1e16 is 2, so the sum is a tie that rounds to the even neighbour, 1e16.

  4. What is the smallest positive subnormal double, and what is its bit pattern? It is 2 to the minus 1,074, with the bit pattern 0x0000000000000001.

  5. What does fma(a, b, c) do differently from a * b + c? It computes the exact product, adds c and rounds once.

  6. Which flag does 1.0 / 0.0 raise, and what is the result? FE_DIVBYZERO, and the result is positive infinity.

  7. Why can -ffast-math break isnan? It enables -ffinite-math-only, which lets the compiler assume no NaN exists and fold the test to false.

Where this fits

This is the third guide in the Fundamentals topic, after the guides to bits and bytes and to integers in C. The related posts in this series go deeper on each part: the stored layout, the 0.1 + 0.2 explanation, special values, comparison and float against double, and later posts cover rounding modes and fesetround, subnormals and flush-to-zero, fused multiply-add, and the other languages that follow the same standard. Everything here applies equally to Rust, Zig and Go, whose f32 and f64 are the same binary32 and binary64 formats, and to the floating-point types of JavaScript and Python, which are doubles.

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.