float
Type¶b = 42.0
id(b)
139923238853936
type(b)
float
b
42.0
42.
42.0
float(42)
42.0
float("42")
42.0
1 / 3
0.3333333333333333
40.0 + 2
42.0
1.23e0
1.23
1e0
1.0
1e3 # = thousands
1000.0
1e-3 # = milli
0.001
float("nan") # also float("NaN")
nan
float("inf") # also float("+inf")
inf
float("-inf")
-inf
float("nan") == float("nan")
False
42 + float("nan")
nan
float("inf") == float("inf")
True
float("inf") + 42 == float("inf")
True
float("inf") + float("-inf")
nan
float("inf") - float("inf")
nan
1e15 + 1
1000000000000001.0
1e16 + 1
1e+16
from math import sqrt
sqrt(2) ** 2
2.0000000000000004
0.1 + 0.2
0.30000000000000004
sqrt(2) ** 2 == 2
False
0.1 + 0.2 == 0.3
False
threshold = 1e-15
abs((sqrt(2) ** 2) - 2) < threshold
True
abs((0.1 + 0.2) - 0.3) < threshold
True
format(0.1, ".50f")
'0.10000000000000000555111512312578270211815834045410'
format(0.2, ".50f")
'0.20000000000000001110223024625156540423631668090820'
format(0.3, ".50f")
'0.29999999999999998889776975374843459576368331909180'
format(1 / 3, ".50f")
'0.33333333333333331482961625624739099293947219848633'
roughly_a_third = round(1 / 3, 5)
roughly_a_third
0.33333
format(roughly_a_third, ".50f")
'0.33333000000000001517008740847813896834850311279297'
format(0.125, ".50f")
'0.12500000000000000000000000000000000000000000000000'
format(0.25, ".50f")
'0.25000000000000000000000000000000000000000000000000'
0.125 + 0.125 == 0.25
True
one_eighth = 1 / 8
one_eighth.hex()
'0x1.0000000000000p-3'
one_eighth.as_integer_ratio()
(1, 8)
roughly_a_third.hex()
'0x1.555475a31a4bep-2'
roughly_a_third.as_integer_ratio()
(3002369727582815, 9007199254740992)