# 4.2. Precision¶

## 4.2.1. Rationale¶

>>> 0.1
0.1

>>> 0.2
0.2

>>> 0.3
0.3

>>> 0.1 + 0.2 == 0.3
False

>>> 0.1 + 0.2
0.30000000000000004

>>> round(0.1+0.2, 16) == 0.3
True

>>> round(0.1+0.2, 17) == 0.3
False


## 4.2.2. IEEE 754 standard¶

>>> 1.234 == 1234 * 10e-4
True

>>> 1234 * 10e-4
1.234


Figure 4.13. What is float as defined by IEEE 754 standard

Figure 4.14. Points chart

Figure 4.15. How computer store float? As defined by IEEE 754 standard

Figure 4.16. How to read/write float from/to memory?

Figure 4.17. Normalized Line

## 4.2.3. Solutions¶

• Round values to 4 decimal places (generally acceptable)

• Store values as int, do operation and then divide. For example instead of 1.99 USD, store price as 199 US cents

• Use Decimal type

• Decimal type is much slower

Listing 4.123. Problem
candy = 0.10      # price in dollars
cookie = 0.20     # price in dollars

print(result)
# 0.30000000000000004

Listing 4.124. Round values to 4 decimal places (generally acceptable)
candy = 0.10      # price in dollars
cookie = 0.20     # price in dollars

result = round(candy + cookie, 4)
print(result)
# 0.3

Listing 4.125. Store values as int, do operation and then divide.
candy = 10        # price in cents
cookie = 20       # price in cents

result = (candy + cookie) / 100   # divide by 100 (number of cents in dollar)
print(result)
# 0.30

Listing 4.126. Use Decimal type
from decimal import Decimal

candy = Decimal('0.10')     # price in dollars
cookie = Decimal('0.20')    # price in dollars