12.5. Math Precision¶
12.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
12.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
12.5.3. Not-a-Number¶
float('nan')
# nan
float('-nan')
# nan
12.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
12.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
12.5.6. IEEE 754 standard¶

Figure 12.3. What is float
as defined by IEEE 754 standard¶

Figure 12.4. Points chart¶

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

Figure 12.6. How to read/write float
from/to memory?¶

Figure 12.7. Normalized Line¶
12.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
12.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