Skip to content
Minute Campus.

Everyday computer scienceLesson 011 min

Why does your computer think 0.1 + 0.2 is not 0.3?

Computers store decimals in sixty-four bits, and in binary one tenth never ends, so the computer keeps the closest value that fits. In most programming languages, 0.1 plus 0.2 then gives 0.3, fifteen zeros, then a 4, because the tiny errors show up at the end. This is not a bug. It is why two decimals should not be tested for an exact match.

Remember

Do not test two decimals for an exact match.

Transcript

The lesson, word for word.

Read it at your own pace, or search the page for a term.

Ask a computer to add zero point one and zero point two. In most programming languages, the answer is not zero point three. It is zero point three, then fifteen zeros, then a four. This is not a bug. Try writing one third as a decimal. Zero point three three three, for ever. You have to stop somewhere, so what you write is slightly off. Computers have the same problem, but they count in binary: in halves, quarters and eighths. And in binary, one tenth is a number that never ends. So the computer stores the closest value that fits in sixty-four bits. Add two of those rounded values, and the tiny errors show up at the end. Usually nobody notices. But it is why you should not test two decimals for an exact match, and why money is often stored as whole cents. The computer is not bad at maths. It ran out of room.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.