Eli5: Programmers, why does “0.15 == 0.150000000000000001” equals = True after 15 zeros?

207 views

Eli5: Programmers, why does “0.15 == 0.150000000000000001” equals = True after 15 zeros?

In: 13

5 Answers

Anonymous 0 Comments

Short answer: It’s because numbers are stored in binary on computers.

Long answer: decimal numbers are represented by adding up powers of 10. 0.15 is actually 1/10 + 5/100. But there are some numbers that can’t be accurately represented that way. Have you ever done 1/3 on a calculator and seen 0.3333333333…? It goes on forever because it’s not possible to exactly represent 1/3 as a sum of powers of 10 (technically powers of 1/10). It’s 3/10 + 3/100 + 3/1000 + 3/10000 … forever.

Now back to 0.15. We can represent that exactly with powers of 1/10, but computers have to store it in powers of 1/2 because they work in binary. So you can come close… 0.15 = 1/8 + 1/64 + 1/128 …, but it can’t be represented exactly. 0.15 would be a repeating decimal in base 2. So the computer stores it as close as it can, and when you convert it back to a readable base 10 format, you get a little bit left over because of the loss of precision.

You are viewing 1 out of 5 answers, click here to view all answers.