Advanced

How a decimal is stored

A decimal number is stored as a sign, a fraction, and a shift, in a fixed number of bits. That fixed width is why some decimals are rounded and why a huge one can become infinity.

What you will see

1e+20

About 1 min of reading

Try It

Probe the limits of a float.

1

Print a tenth sum to see the rounding.

print(0.1 + 0.2)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0.30000000000000004
2

Multiply past the largest float.

print(1e308 * 10)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
inf
3

Print a third and see it cut off.

print(1 / 3)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0.3333333333333333
4

Add a tiny number to a huge one.

print(1e20 + 1)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
1e+20
The 1 is past the precision the float can hold, so it is lost.

Data Flow

A float stores a sign, a fraction, and an exponent in fixed bits, so it has limited precision and a maximum size.
1 sign and fraction and exponent
↓
2 a tenth is rounded
↓
3 the exponent runs out
↓
4 past the top is infinity
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

print(0.1 + 0.2) 0.30000000000000004
Why this works
Fixed precision

A float has a fixed number of fraction bits, so it carries a fixed count of digits of accuracy. Adding a tiny number to a huge one can change nothing at all.

When to avoid floats

For exact money or counts, keep whole numbers. Floats are for measured quantities where a tiny error is acceptable, which is most science and graphics.

Examples

The three parts

print(1e308)
print(1e-308)

A float is a sign, a fraction, and an exponent that shifts it. The exponent is what lets one width hold tiny and huge numbers.

The rounding again

print(0.1 + 0.2)

A tenth has no exact binary fraction, so the nearest one that fits is stored. The sum shows that rounding, which is the same fact from the values subject.

The top of a float

print(1e308 * 10)

Past the largest float, multiplying gives infinity. The exponent runs out of bits, and the value has no room.

Not a whole number

print(1 / 3)

A third is an endless binary fraction cut off at the width. The stored value is the closest that fits, not the true third.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← The limit of a fixed width
Previous Lesson
The limit of a fixed width
Next Lesson
Encodings and why they differ
Encodings and why they differ →