Mathew K Analytics

Lesson 2 · Python data types deep dive

Python Floats Explained: Precision, Rounding & Pitfalls | Data Types #2

Video two of the twelve-part series: the second numeric type, and where it genuinely diverges from int. Every literal form, every operator, the precision…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python Data Types Deep-Dive, Video 2: Floats (float)#

  • Video two of the twelve-part series: the second numeric type, and where it genuinely diverges from int.
  • Every literal form, every operator, the precision problem that trips up nearly every beginner, and all seven public float methods.
  • Let's get into it.

Part 1: What Makes float Different#

temperature = 98.6
negative_float = -3.14
scientific = 6.022e23
print(type(temperature))
print(scientific)
<class 'float'>
6.022e+23

Part 2: Float Literals#

a = 3.14159
b = .5
c = 5.
d = 1_234.567_8
e = 1.5e-3
f = 1.5E10
print(a, b, c, d, e, f)
3.14159 0.5 5.0 1234.5678 0.0015 15000000000.0

Part 3: Arithmetic Operators#

a, b = 7.5, 2.0
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
print(5 + 2.0)
9.5
5.5
15.0
3.75
3.0
1.5
56.25
7.0

Part 4: The Precision Problem#

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(f'{0.1:.20f}')
print(f'{0.3:.20f}')
0.30000000000000004
False
0.10000000000000000555
0.29999999999999998890
import math
print(math.isclose(0.1 + 0.2, 0.3))
print(round(0.1 + 0.2, 10) == round(0.3, 10))
True
True

Part 5: Comparison Operators#

print(3.5 < 5.1)
print(5.0 == 5)
print(1.0 < 5.5 < 10.0)
print(float('inf') > 999999999999.9)
True
True
True
True

Part 6: Converting Values to float#

print(float('3.14'))
print(float('  3.14  '))
print(float('1e3'))
print(float(5))
print(float(True))
print(float('inf'))
print(float('-inf'))
print(float('nan'))
3.14
3.14
1000.0
5.0
1.0
inf
-inf
nan
try:
    float('not a number')
except ValueError as e:
    print(f'Caught: {e}')
Caught: could not convert string to float: 'not a number'

Part 7: Built-in Functions That Work With float#

print(abs(-3.7))
print(round(2.5))
print(round(3.5))
print(round(2.675, 2))
print(pow(2.0, 0.5))
print(min(3.1, 2.9, 4.4))
print(max(3.1, 2.9, 4.4))
print(sum([1.1, 2.2, 3.3]))
3.7
2
4
2.67
1.4142135623730951
2.9
4.4
6.6

Part 8: is_integer()#

print((5.0).is_integer())
print((5.5).is_integer())
print((-3.0).is_integer())
print((0.0).is_integer())
True
False
True
True

Part 9: as_integer_ratio()#

print((0.5).as_integer_ratio())
print((0.25).as_integer_ratio())
print((0.1).as_integer_ratio())
print((2.0).as_integer_ratio())
(1, 2)
(1, 4)
(3602879701896397, 36028797018963968)
(2, 1)

Part 10: hex()#

value = 3.14159
print(value.hex())
print((1.0).hex())
print((0.5).hex())
print((0.0).hex())
0x1.921f9f01b866ep+1
0x1.0000000000000p+0
0x1.0000000000000p-1
0x0.0p+0

Part 11: fromhex()#

value = 3.14159
hex_string = value.hex()
reconstructed = float.fromhex(hex_string)
print(reconstructed)
print(reconstructed == value)
print(float.fromhex('0x1.8p+1'))
3.14159
True
3.0

Part 12: real and imag#

value = 3.14
print(value.real)
print(value.imag)
print(type(value.real))
3.14
0.0
<class 'float'>

Part 13: conjugate()#

print((3.14).conjugate())
print((-2.5).conjugate())
3.14
-2.5

Part 14: Special Values: inf, -inf, and nan#

positive_infinity = float('inf')
negative_infinity = float('-inf')
not_a_number = float('nan')
print(positive_infinity)
print(1 / positive_infinity)
print(positive_infinity + 1)
print(positive_infinity == negative_infinity)
print(not_a_number == not_a_number)
inf
0.0
inf
False
False
import math
print(math.isnan(not_a_number))
print(math.isinf(positive_infinity))
print(math.isfinite(3.14))
print(0.0 / 1.0)
try:
    1.0 / 0.0
except ZeroDivisionError as e:
    print(f'Caught: {e}')
True
True
True
0.0
Caught: float division by zero

Part 15: Formatting Floats#

value = 1234.56789
print(f'{value:.2f}')
print(f'{value:.0f}')
print(f'{value:,.2f}')
print(f'{value:e}')
print(f'{value:.2e}')
print(f'{0.4567:.1%}')
print(f'{value:12.2f}')
print(f'{value:+.2f}')
1234.57
1235
1,234.57
1.234568e+03
1.23e+03
45.7%
     1234.57
+1234.57

Part 16: Rounding Pitfalls in Depth#

for value in [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]:
    print(f'{value} rounds to {round(value)}')
0.5 rounds to 0
1.5 rounds to 2
2.5 rounds to 2
3.5 rounds to 4
4.5 rounds to 4
5.5 rounds to 6
from decimal import Decimal, ROUND_HALF_UP
value = Decimal('2.5')
print(value.quantize(Decimal('1'), rounding=ROUND_HALF_UP))
price_a = Decimal('19.99')
price_b = Decimal('5.01')
print(price_a + price_b)
3
25.00

Part 17: Immutability#

value = 3.14
print(id(value))
value = value + 1.0
print(id(value))
2542658413680
2542660158224

Part 18: Common Patterns and Pitfalls#

total = 0.0
for _ in range(10):
    total += 0.1
print(total)
print(total == 1.0)
import math
print(math.isclose(total, 1.0))
0.9999999999999999
False
True
def safe_range(start, stop, step):
    values = []
    current = start
    count = 0
    while count < round((stop - start) / step):
        values.append(round(current, 10))
        current += step
        count += 1
    return values
print(safe_range(0.0, 1.0, 0.1))
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Wrap-Up: What You Learned#

  • Float literals: decimal point, scientific notation, underscores, leading and trailing dots.
  • Arithmetic operators, and why mixing int and float always promotes to float.
  • The precision problem: why 0.1 + 0.2 != 0.3, and using math.isclose or decimal instead.
  • Converting to float with float(), including inf, -inf, and nan strings.
  • Built-in functions and banker's rounding: why round(2.5) is 2, not 3.
  • All seven public float methods: is_integer, as_integer_ratio, hex, fromhex, real, imag, and conjugate.
  • The three IEEE special values: inf, -inf, and nan, and how to test for each correctly.
  • Formatting floats, rounding pitfalls, immutability, and why real money math needs the decimal module.
  • Next up: complex numbers, the third and final built-in numeric type.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.