Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why does -22 // 10 return -3 in Python?
In Python, -22 // 10 returns -3 because of how floor division works with negative numbers. The // operator always rounds down toward negative infinity, not toward zero.
Understanding Floor Division
Floor division (//) returns the largest integer less than or equal to the division result. For positive numbers, this behaves as expected, but with negative numbers, it rounds away from zero toward negative infinity.
Syntax
a // b
Where a and b are the dividend and divisor respectively.
Floor Division with Positive Numbers
a = 22
b = 10
print("22 / 10 =", 22 / 10)
print("22 // 10 =", 22 // 10)
22 / 10 = 2.2 22 // 10 = 2
Floor Division with Negative Numbers
Here's where the behavior differs from truncation toward zero ?
a = -22
b = 10
print("-22 / 10 =", -22 / 10)
print("-22 // 10 =", -22 // 10)
-22 / 10 = -2.2 -22 // 10 = -3
Why -22 // 10 Returns -3
Let's break down what happens step by step ?
import math
# Regular division gives us the exact result
exact_result = -22 / 10
print("Exact division: -22 / 10 =", exact_result)
# Floor function rounds down to nearest integer
floor_result = math.floor(exact_result)
print("Floor of -2.2 =", floor_result)
# Floor division does the same thing
floor_div_result = -22 // 10
print("Floor division: -22 // 10 =", floor_div_result)
Exact division: -22 / 10 = -2.2 Floor of -2.2 = -3 Floor division: -22 // 10 = -3
Comparison with Different Division Methods
| Operation | Result | Description |
|---|---|---|
-22 / 10 |
-2.2 | True division (float result) |
-22 // 10 |
-3 | Floor division (rounds down) |
int(-22 / 10) |
-2 | Truncation toward zero |
Visualizing the Difference
# Comparing different approaches
numbers = [22, -22]
divisor = 10
for num in numbers:
regular_div = num / divisor
floor_div = num // divisor
truncated = int(num / divisor)
print(f"{num} / {divisor}:")
print(f" Regular division: {regular_div}")
print(f" Floor division: {floor_div}")
print(f" Truncation: {truncated}")
print()
22 / 10: Regular division: 2.2 Floor division: 2 Truncation: 2 -22 / 10: Regular division: -2.2 Floor division: -3 Truncation: -2
Conclusion
Floor division // always rounds toward negative infinity, not toward zero. This is why -22 // 10 returns -3 instead of -2 it's the largest integer less than -2.2.
