Who’s exploring?

DISCOVER · ARTICLE

Your computer cannot write down one tenth

The number 0.1 is a tidy fraction for us and an endless one for a computer.

A test that fails

Ask Python whether 0.1 + 0.1 + 0.1 equals 0.3 and it answers False. The same thing happens in most programming languages, because it comes from how computers store numbers, not from a bug in one of them.

Python's own documentation uses exactly this example to explain the effect.

Why one tenth is awkward

Computers store fractions in base 2. In base 2, one tenth is an infinitely repeating pattern, 0.0001100110011..., in the same way that one third repeats forever as 0.333... in base 10.

A computer has to cut that pattern off after a fixed number of bits. So what it keeps is a close neighbour of one tenth, not one tenth itself.

What is actually stored

On most machines the stored value for 0.1 is the fraction 3602879701896397 divided by 2 to the power 55. Written out in decimal, that is 0.1000000000000000055511151231257827..., which is a hair above one tenth.

The 0.3 you type is also a rounded neighbour of three tenths. Add three slightly-off tenths and compare against a slightly-off three tenths, and the two tiny errors do not cancel exactly. Rounding your inputs first does not help either, since each input is still a binary approximation.

How programmers cope

They compare numbers with a small allowed gap instead of asking for exact equality. Python offers math.isclose for this. When exact decimal results matter, as with money, there are separate tools: Python's decimal module works in base 10, and its fractions module keeps exact ratios.

Keep reading? Spark picked your next article.

The 128 symbols behind every text fileMore about Computing

More in Computing

— forget which articles you’ve read on this device.

Sources, credits & transparency

Report a mistake on this page