16.5. Math Precision

16.5.1. Minimal and Maximal Values

Maximal and minimal float values:

import sys

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

16.5.2. Infinity

Infinity representation:

1e308                   # 1e+308
-1e308                  # -1e+308

1e309                   # inf
-1e309                  # -inf

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

float('Infinity')       # inf
float('-Infinity')      # -inf

16.5.3. Not-a-Number

float('nan')
# nan

float('-nan')
# nan

16.5.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

16.5.5. Floating Numbers Precision

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
0.1 + 0.1
# 0.2

0.1 + 0.1 + 0.1
# 0.30000000000000004
round(0.1+0.2, 16)
# 0.3

round(0.1+0.2, 17)
# 0.30000000000000004
round(0.1+0.2, 16)
# True

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

16.5.6. IEEE 754 standard

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

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

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

Figure 16.4. Points chart

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

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

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

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

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

Figure 16.7. Normalized Line

16.5.7. Floats in Doctest

def add(a, b):
    """
    >>> add(1.0, 2.0)
    3.0

    >>> add(0.1, 0.2)
    0.30000000000000004

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

16.5.8. Decimal Type

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