Understanding Floating-Point Numbers

This entry is mostly interactive, and needs JavaScript. There are fifteen demos. Nearly all of them share one number: change it in any of them and the rest follow. Nothing leaves your browser.

Spoiler: a floating-point number is a short row of bits and a note saying where to put the point. Every strength and every weakness follows from how short the row is.

As a convenience, an automatically created video version of this blog post can be viewed on YouTube.

CS101

A binary integer is a row of bits. Each is either off and worth nothing, or on and worth 2position, counting positions from zero at the right. Here are sixteen of them. Click the bits.

The demo loads here, if JavaScript is on.

Why stop at 20? A negative power is a fraction: 2-3 is 1/8. Give half of the sixteen bits to those and you have a fixed-point number. The dotted line is the binary point: whole numbers to its left, fractions to its right.

The demo loads here, if JavaScript is on.

It holds nothing above 256 and nothing finer than 1/256, for ever. That is the problem with a point that is fixed.

Let Your Float Bit Slide 🎶

An infinite number of mathematicians walk into a bar. The first orders a beer, the second orders half a beer, the third orders a quarter of a beer, and so on. The bartender pours two beers and says “know your limits.”

So let the point float. Spend a few bits on an exponent that says where the window of powers sits, one on a sign, and the rest on the fraction: the bits inside the window. Slide the exponent and watch the labels move.

The demo loads here, if JavaScript is on.
  • The window is always the same width. Slide it up for big numbers and the smallest bit is worth more, so the steps get coarser. Slide it down and they get finer.
  • The hidden bit. In binary the first digit that matters is always a 1, so it isn’t stored. That box is free precision.
  • Zero can’t have a leading 1, so it gets a code of its own: everything off.
  • The lowest exponent is special. The hidden bit becomes a 0 there. Those are the subnormals, and the next demo shows what they’re for.
  • The highest exponent is special too. With the fraction all off it means infinity, and with anything else it means NaN.
  • The exponent is stored with a bias, as the plain number you’d get by adding 127 for single precision, or 15 for half. The strip under the demo shows the bits as they really sit in memory.

Every Number, on One Line

A real float has too many values to draw. One with six bits doesn’t. This is all of them.

The demo loads here, if JavaScript is on.

The ticks are evenly spaced within each colour, and the spacing doubles at every power of two. That one picture is most of what there is to know: a float gives you the same number of significant digits everywhere, not the same number of decimal places.

Now choose “Close to zero” and switch the subnormals off. There is a hole around zero, far wider than the gaps beside it. Subnormals fill it in with evenly spaced values, and that buys a guarantee worth having: if two numbers are different, subtracting one from the other never gives zero.

The Sizes It Comes In

Nine formats, each a different split of the same three parts. More exponent bits buy range. More fraction bits buy precision.

The demo loads here, if JavaScript is on.
  • Double precision (binary64, FP64). Every number in JavaScript is one of these, including the counter in your for loop. That’s fine: it holds every whole number up to 253, which is 9,007,199,254,740,992, exactly.
  • Single precision (binary32, FP32). Half the memory, and what you reach for when speed matters: one AVX2 instruction works on eight of them at once, and a GPU gets through trillions a second. Exact for whole numbers up to 224, which is 16,777,216. Past that it counts in twos, then fours, then eights.
  • Half precision (binary16, FP16). Twice as many parameters in the same memory, and often enough precision for a neural network.
  • BFloat16 (BF16). Sixteen bits again, but with FP32’s eight exponent bits and only seven for the fraction. All of FP32’s range and much less of its precision. It is seen in some machine learning scenarios, such as with the nvidia H100 where you can yield almost 2,000 TFLOPs using BF16 on tensor cores1.
  • TensorFloat-32 (TF32). A misnomer, as it isn’t 32 bits: it’s nineteen, with the range of an FP32 and the precision of an FP16. It exists inside nvidia’s tensor cores.
  • FP8, in two variants. E4M3 has four exponent bits and three fraction bits, and E5M2 has five and two.
  • FP4, in two variants. E2M1 and E3M0. This is really pushing the limits, but it can be seen where layers of models are quantized to such tiny types. Zero fraction bits sounds impossible, but the hidden bit is still there.

The small ones bend the rules to waste less. E4M3 has no infinity and gives up only a single pattern for NaN. E2M1 has neither, so all sixteen patterns are numbers2.

What Did I Actually Store?

Type a number. Most decimal fractions can’t be written exactly in binary, in the same way a third can’t be written exactly in decimal, so what gets stored is the nearest thing the format has.

The demo loads here, if JavaScript is on.

Try 0.1, then 0.5. A half is a power of two and is stored exactly. A tenth is not, in any binary format of any size. Then try 16,777,217 in FP32, and 9,007,199,254,740,993 in FP64: the first whole numbers each one can’t hold.

That second one bites in practice. A 64-bit database ID sent as a JSON number arrives in a browser as an FP64, and the last digits can change on the way. It’s why APIs that hand out big IDs send them a second time as strings3.

If 0.1 isn’t stored as 0.1, why does it print as 0.1? Because printing looks for the shortest decimal that reads back as the same bits, and stops there.

The demo loads here, if JavaScript is on.

How Big Is a Step?

The gap between one stored number and the next depends on how big the number is. Whether that matters depends on what the number means.

The demo loads here, if JavaScript is on.

To present an extreme example, the population of the Earth in single precision can only be counted in steps of 512. The larger the magnitude, the coarser the precision.

Where the Arithmetic Slips

Every operation is done as if exactly, and then rounded to the nearest number the format has4. One rounding is harmless. They add up.

The demo loads here, if JavaScript is on.

This is why you don’t compare floats with a plain equals. Ask whether they are within a few steps of each other instead, and scale the tolerance to the size of the numbers: a fixed 0.00001 is far too loose near zero and far too tight near a billion.

Do it ten million times and it stops being a rounding error.

The demo loads here, if JavaScript is on.

Try 0.25 as well. It is stored exactly, so nothing goes wrong, until the total is big enough that a quarter falls below its step size and is rounded away.

That same absorption means addition isn’t associative. The order you add in is part of the answer.

The demo loads here, if JavaScript is on.

It’s why a sum can differ between a debug build and a release build, or between one thread and eight.

And the worst one: subtracting two numbers that are nearly equal. The digits they share cancel, and what’s left is mostly the rounding.

The demo loads here, if JavaScript is on.

The cure is never more precision. It’s rearranging the sum so the subtraction doesn’t happen.

The Odd Ones

Infinity and NaN aren’t errors. They’re values, with rules, and the rules are occasionally surprising.

The demo loads here, if JavaScript is on.

NaN is the only value that isn’t equal to itself, which is the standard way to test for it.

Small Floats for Big Models

Machine learning has unique needs. Many models are comprised of billions of parameters, and how many of them fit in memory decides what you can run. So the question becomes how few bits a weight can get away with. First, how far each format reaches:

The demo loads here, if JavaScript is on.

Try the small gradient. FP16 runs out at about 6 × 10-8, and gradients in a deep network go below that routinely. Training in FP16 only works by multiplying the loss by a large constant first and dividing it back out afterwards. BF16 has FP32’s exponent and simply doesn’t have the problem, which is most of why it won for training.

Then, what happens to a layer of weights when you squeeze them.

The demo loads here, if JavaScript is on.
  • A float spends its values where the weights are. Its levels crowd in around zero, and so does a bell curve. Compare FP8 with INT8, whose levels are evenly spread.
  • FP4 as-is is useless. Its smallest value is a half, so ordinary weights all round to zero.
  • So share a scale. Give a block of weights one common power of two, and four bits each start to say something. This is how the four-bit formats are used in practice.

Basic Things You Should Know About Floating-Point Numbers

  • Floats are not vague. Single precision holds every whole number from -16,777,216 to 16,777,216 with zero ambiguity, and plenty of fractions too: 0.25, 0.75 and 0.0042572021484375 are all stored exactly. The key is that the number is a fraction whose denominator is a power of 2, and that it fits within the precision band of its magnitude.
  • Double precision does the same up to 9,007,199,254,740,992. Between 1 and 2 its steps are 1/4,503,599,627,370,496, which for the vast majority of uses is well within any reasonable bounds.
  • Every number in JavaScript is a double, apart from BigInt. Your counter and other seeming integers are doubles. The bitwise operators treat it as a signed 32-bit integer for the duration, as a hack.
  • Precision is relative. You get about 7 significant digits in single and about 16 in double, wherever the point happens to be.
  • Errors come from the arithmetic, not the storage. One rounding is nothing. A long sum, or one subtraction of near-equals, is where it goes wrong.
  • Decimal types can be mandated in some domains, but represent a dramatic speed compromise, courtesy of the reality that our hardware is extremely optimized for floating-point math. With some analysis of the precision for a given task, and intelligent rounding rules, double precision is more than adequate for most purposes. There are scenarios where you can pursue a hybrid approach: in an extremely high Internal Rate of Return calculation I use floating point to get to an approximate solution, and then decimal math for the final, smallest leg. And even an infinitely large decimal type can’t store 1/3.

Footnotes

  1. With sparsity. Without it, it achieves about half the calculation throughput. ↩

  2. The four-bit E2M1 values are 0, 0.5, 1, 1.5, 2, 3, 4 and 6, and their negatives. That is the whole format. ↩

  3. Twitter’s API is the well-known case: every id came with an id_str beside it for exactly this reason. ↩

  4. When the exact answer is precisely half way between two neighbours, it goes to the one whose last bit is 0. Always rounding halves up would push every long calculation slowly upward. ↩