- Python Language Incompatibilities moving from Python 2 to Python 3 Integer Division
- Mastering Integer Division in Python
- What is Integer Division?
- Integer Division
- Division vs. Integer Division
- Conversion between Integer and Float
- Integer division and remainder
- Python integer division by zero
- Python integer division ceiling
- Python integer division too large for a float
- Integer division python round up
- Python integer division vs floor
- FAQs
- Conclusion
Python Language Incompatibilities moving from Python 2 to Python 3 Integer Division
The standard division symbol ( / ) operates differently in Python 3 and Python 2 when applied to integers.
When dividing an integer by another integer in Python 3, the division operation x / y represents a true division (uses __truediv__ method) and produces a floating point result. Meanwhile, the same operation in Python 2 represents a classic division that rounds the result down toward negative infinity (also known as taking the floor).
Code | Python 2 output | Python 3 output |
---|---|---|
3 / 2 | 1 | 1.5 |
2 / 3 | 0 | 0.6666666666666666 |
-3 / 2 | -2 | -1.5 |
The rounding-towards-zero behavior was deprecated in Python 2.2, but remains in Python 2.7 for the sake of backward compatibility and was removed in Python 3.
Note: To get a float result in Python 2 (without floor rounding) we can specify one of the operands with the decimal point. The above example of 2/3 which gives 0 in Python 2 shall be used as 2 / 3.0 or 2.0 / 3 or 2.0/3.0 to get 0.6666666666666666
Code | Python 2 output | Python 3 output |
---|---|---|
3.0 / 2.0 | 1.5 | 1.5 |
2 / 3.0 | 0.6666666666666666 | 0.6666666666666666 |
-3.0 / 2 | -1.5 | -1.5 |
There is also the floor division operator ( // ), which works the same way in both versions: it rounds down to the nearest integer. (although a float is returned when used with floats) In both versions the // operator maps to __floordiv__ .
Code | Python 2 output | Python 3 output |
---|---|---|
3 // 2 | 1 | 1 |
2 // 3 | 0 | 0 |
-3 // 2 | -2 | -2 |
3.0 // 2.0 | 1.0 | 1.0 |
2.0 // 3 | 0.0 | 0.0 |
-3 // 2.0 | -2.0 | -2.0 |
One can explicitly enforce true division or floor division using native functions in the operator module:
from operator import truediv, floordiv assert truediv(10, 8) == 1.25 # equivalent to `/` in Python 3 assert floordiv(10, 8) == 1 # equivalent to `//`
While clear and explicit, using operator functions for every division can be tedious. Changing the behavior of the / operator will often be preferred. A common practice is to eliminate typical division behavior by adding from __future__ import division as the first statement in each module:
# needs to be the first statement in a module from __future__ import division
from __future__ import division guarantees that the / operator represents true division and only within the modules that contain the __future__ import, so there are no compelling reasons for not enabling it in all new modules.
Note: Some other programming languages use rounding toward zero (truncation) rather than rounding down toward negative infinity as Python does (i.e. in those languages -3 / 2 == -1 ). This behavior may create confusion when porting or comparing code.
Note on float operands: As an alternative to from __future__ import division , one could use the usual division symbol / and ensure that at least one of the operands is a float: 3 / 2.0 == 1.5 . However, this can be considered bad practice. It is just too easy to write average = sum(items) / len(items) and forget to cast one of the arguments to float. Moreover, such cases may frequently evade notice during testing, e.g., if you test on an array containing float s but receive an array of int s in production. Additionally, if the same code is used in Python 3, programs that expect 3 / 2 == 1 to be True will not work correctly.
See PEP 238 for more detailed rationale why the division operator was changed in Python 3 and why old-style division should be avoided.
See the Simple Math topic for more about division.
PDF — Download Python Language for free
Mastering Integer Division in Python
As a high-level, dynamically typed language, Python provides a range of data types to work with, including integer, float, and complex numbers. In this article, we’ll focus on integer division in Python, exploring the concept and how it works.
What is Integer Division?
Integer division is a mathematical operation that divides two integers and returns an integer result. The result is rounded down to the nearest whole number, discarding any fractional part. In other words, integer division rounds down the result to the nearest integer, providing the floor value of the division.
Integer Division
In Python, integer division is represented using the // operator. When two integers are divided using this operator, the result is the floor value of the division, i.e. the largest integer that is less than or equal to the actual result.
For example, consider the following code:
The output of the above code will be 3 .
It’s important to note that division with integers in Python 3 works differently than in Python 2. In Python 2, the / operator performs integer division if both operands are integers. In Python 3, the / operator always performs floating-point division, while the // operator performs integer division.
To get integer division in Python 2, you can use the // operator or convert the operands to float before division.
For example:
print(10.0 // 3) print(10 // 3.0) print(10.0 / 3) print(10 / 3.0)
In all of these cases, the result will be a floating-point number, not an integer.
Division vs. Integer Division
It’s important to understand the difference between division and integer division, as they can produce different results. Consider the following example:
The output of the first line will be 3.333333. , while the output of the second line will be 3 . In other words, division returns a floating-point number, while integer division returns an integer.
Conversion between Integer and Float
In some cases, you may need to convert an integer to a float or a float to an integer. This can be done using the int() and float() functions in Python.
For example:
The output of the first line will be 10.0 , and the output of the second line will be 10 .
Integer division and remainder
The // operator performs integer division, which means that it returns the quotient of the division, discarding any remainder. For example, 7 // 2 would return 3 , since 7 divided by 2 is 3 with a remainder of 1.
The % operator returns the remainder of the division. For example, 7 % 2 would return 1 , since 7 divided by 2 is 3 with a remainder of 1.
Here is an example that demonstrates the use of these operators:
a = 7 b = 2 quotient = a // b remainder = a % b print("The quotient of", a, "divided by", b, "is", quotient) print("The remainder of", a, "divided by", b, "is", remainder)
The quotient of 7 divided by 2 is 3
The remainder of 7 divided by 2 is 1
Python integer division by zero
In Python, integer division by zero raises a ZeroDivisionError . This error occurs when you attempt to divide an integer by zero, either explicitly or as a result of some calculation.
Here is an example of code that would raise a ZeroDivisionError :
a = 10 b = 0 c = a // b # integer division by zero # the following code will not be executed since an error has occurred print("The result of the division is:", c)
ZeroDivisionError: integer division or modulo by zero
To avoid this error, you can check whether the denominator is zero before performing the division.
Python integer division ceiling
In Python, to get the ceiling value of the result of an integer division, you can use the math module and its ceil function. The ceil function takes a single argument, which is a floating-point number, and returns the smallest integer that is greater than or equal to the argument.
To use math.ceil() to calculate the ceiling value of an integer division, you need to first convert the dividend and divisor to floating-point numbers. Here is an example:
import math a = 7 b = 2 quotient = a / b ceiling = math.ceil(quotient) print("The result of the division is:", quotient) print("The ceiling value of the division is:", ceiling)
The result of the division is: 3.5
The ceiling value of the division is: 4
In this example, a and b are both integers. We first perform the division a / b , which results in a floating-point number with a value of 3.5. We then pass this result to math.ceil() , which returns the ceiling value of 4.
Python integer division too large for a float
In Python, if you perform an integer division that results in a quotient that is too large to be represented as a float, you will get an OverflowError . This error occurs when the resulting quotient or remainder is too large to be represented by the floating-point format used by Python.
Here is an example of code that would raise an OverflowError :
a = 10**1000 b = 1 c = a // b # integer division with a very large dividend # the following code will not be executed since an error has occurred print("The result of the division is:", c)
OverflowError: integer division result too large for a float
Integer division python round up
In Python, to perform integer division and round up to the nearest integer, you can use the math module and its ceil function. The ceil function returns the smallest integer greater than or equal to the input.
We can also use the ‘//’ operator to perform integer division and then add 1 to the result if there is a remainder.
Python integer division vs floor
Here’s a comparison table between Python’s integer division ( // ) and floor division ( math.floor() ):
Feature | Integer division ( // ) | Floor division ( math.floor() ) |
Operation | Performs integer division and rounds towards zero | Rounds down to the nearest integer |
Input type | Accepts integer inputs only | Accepts inputs of any numeric type |
Negative numbers | Rounds towards zero | Rounds down |
Positive numbers | Same result as floor division | Same result as integer division |
Return type | Returns an integer | Returns a float |
Type of operator | Built-in operator | Function in the math module |
Comparison table between integer division and floor
Integer division only works with integer inputs, while floor division can accept inputs of any numeric type.
FAQs
If the operands of integer division in Python are floating-point numbers, the result will be a floating-point number. The // operator can be used to perform integer division with floating-point numbers.
No, integer division in Python only returns the floor of the division result, discarding any fractional part.
Conclusion
In this article, we’ve explored the concept of integer division and how it works. We’ve looked at the difference between division and integer division, and how to convert between integers and floats. Whether you’re working with positive or negative numbers, the // operator makes it easy to perform integer division and obtain the desired result. With this understanding, you can use integer division effectively in your code.