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

206 views

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

In: 13

5 Answers

Anonymous 0 Comments

When creating software, you have two choices:

– (a) Track decimal numbers to limited accuracy. Pros: Very fast due to hardware support. Always uses a very small, pre-defined amount of memory (8 bytes, 4 bytes, or if you’re an ML hipster, 2 bytes). Good enough for most purposes. Cons: Sometimes new programmers don’t understand, or experienced programmers forget, that the roundoff is a thing. They’re surprised when 0.15 == 0.150000000000000001. Sometimes roundoff causes fundamental issues in real programs (for example, fractal explorer programs tend to break if you zoom in really far), but usually you see more minor issues that you can work around (for example, instead of checking “is x = 5” you check for “is x between 4.999999 and 5.000001” because roundoff might have caused it to be slightly off).
– (b) Track decimal numbers exactly. Pros: No unexpected behavior or information loss. Cons: Could use an unlimited amount of memory — someone could write 15.000000000000 … (1 billion zeros) … 00000001 and you’d need many millions of bytes to store that single number. Calculations need a bunch of loops and checking to deal with numbers of different sizes, which is slow. It’s unclear how to handle square roots or other calculations that have an unlimited number of decimals (typically in addition to square roots, programmers expect general purpose languages to have built-in support for trigonometry, logarithms, and exponentials).

Most programming languages make option (a) the default. Some programming languages also allow Option (b), for example Java’s `BigDecimal` or Python’s `decimal.Decimal`

Here’s what happens when I try your code in Python:

>>> 0.15 == 0.150000000000000001
True

And using the `decimal` library:

>>> from decimal import Decimal
>>> Decimal(“0.15”) == Decimal(“0.150000000000000001”)
False

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