Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is the difference between int and float?
What you need to know
int: exact and unbounded
Python's int has no fixed size. Most languages stop at 64 bits; Python just uses more memory.
1print(2 ** 100) # 12676506002282294014967032053762print(7 / 2) # 3.5 -> true division always gives a float3print(7 // 2) # 3 -> floor division4print(-7 // 2) # -4 -> floors towards minus infinity, not towards 05print(int(-3.7)) # -3 -> int() truncates towards 0float: fast, but binary
A float stores a number as a binary fraction in 64 bits. Just as 1/3 cannot be written exactly in decimal (0.3333...), 0.1 cannot be written exactly in binary. Python stores the nearest possible value and hides the tail when printing:
1from decimal import Decimal2import math34print(Decimal(0.1)) # 0.10000000000000000555111512312578270211815834045410156255print(0.1 + 0.2) # 0.300000000000000046print(0.1 + 0.2 == 0.3) # False7print(math.isclose(0.1 + 0.2, 0.3)) # True8print(round(2.5), round(3.5)) # 2 4 -> ties round to the even numberFloats also have special values: float("inf") and float("nan") (not a number). nan is not equal to anything, even itself, so you test it with math.isnan(x).
In ML you meet smaller floats
NumPy defaults to 64-bit floats, but PyTorch defaults to 32-bit (float32), and models are often trained or served in 16-bit formats (float16, bfloat16) to save GPU memory. Fewer bits means less precision, which is why a model can produce slightly different numbers on different hardware.
A real-life example
A payments dashboard adds up UPI transactions in rupees as floats:
1from decimal import Decimal23total = 0.04for amount in [0.1, 0.2, 0.3]:5 total += amount6print(total, total == 0.6) # 0.6000000000000001 False78paise = [10, 20, 30] # store money as integer paise9print(sum(paise) / 100) # 0.61011exact = sum([Decimal("0.1"), Decimal("0.2"), Decimal("0.3")])12print(exact, exact == Decimal("0.6")) # 0.6 TrueAcross millions of rows, those tiny errors add up, and a reconciliation check that uses == fails even though no money is missing. The fix used by most payment systems is to store integer paise (or cents) and only format as rupees for display. Build Decimal from strings, not floats — Decimal(0.1) copies the float's error.
Follow-up questions to expect
- "Why is
0.1 + 0.2not0.3?" — Both numbers are stored as the nearest binary fraction, and the two small errors do not cancel, so the sum is the double just above 0.3. - "What is NaN and how do you check for it?" — "Not a Number", the result of undefined maths like
inf - inf. Usemath.isnan(x), becausenan == nanisFalse. - "
int(3.9)orround(3.9)?" —inttruncates to 3;roundgives 4. For negatives,int(-3.9)is -3 andmath.floor(-3.9)is -4.