7.5. Math Precision

7.5.1. float min and max

7.5.1.1. Maximal and minimal float values

import sys

sys.float_info.min      # 2.2250738585072014e-308
sys.float_info.max      # 1.7976931348623157e+308

7.5.1.2. Infinity representation

1e308                   # 1e+308
1e309                   # inf
float('inf')            # inf
float('Infinity')       # inf
float('-inf')           # -inf
float('-Infinity')      # -inf

7.5.1.3. Not-a-Number

float('nan')
# nan

float('-nan')
# nan

7.5.1.4. NaN vs Inf

float('inf') + float('inf')     # inf
float('inf') + float('-inf')    # nan
float('-inf') + float('inf')    # nan
float('-inf') + float('-inf')   # -inf

float('inf') - float('inf')     # nan
float('inf') - float('-inf')    # inf
float('-inf') - float('inf')    # -inf
float('-inf') - float('-inf')   # nan

float('inf') * float('inf')     # inf
float('inf') * float('-inf')    # -inf
float('-inf') * float('inf')    # -inf
float('-inf') * float('-inf')   # inf

float('inf') / float('inf')     # nan
float('inf') / float('-inf')    # nan
float('-inf') / float('inf')    # nan
float('-inf') / float('-inf')   # nan

7.5.2. Precision

7.5.2.1. Problem

0.1 + 0.2
# 0.30000000000000004
0.1 + 0.2 == 0.3
# False

7.5.2.2. What is float

../../_images/float-anatomy.png

Figure 21. What is float

7.5.2.3. Points chart

../../_images/float-expression.png

Figure 22. Points chart

7.5.2.4. How computer store float?

../../_images/float-mantissa-1.png

Figure 23. How computer store float?

7.5.2.5. How to read/write float from/to memory?

../../_images/float-mantissa-2.png

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

7.5.2.6. Normalized Line

../../_images/float-normalized.png

Figure 25. Normalized Line

7.5.3. doctests

def add_numbers(a, b):
    """
    >>> add_numbers(2.5, 1.2)
    3.7

    >>> add_numbers(0.1, 0.2)
    0.30000000000000004

    >>> add_numbers(0.1, 0.2)   # doctest: +ELLIPSIS
    0.1 + 0.2 == 0.3000...
    """
    return a + b

7.5.4. decimal

from decimal import Decimal


a = Decimal('0.1')
b = Decimal('0.2')

a + b
# Decimal('0.3')
from decimal import Decimal


a = Decimal('0.3')

float(a)
# 0.3