Cookie Policy

We use cookies to operate this website, improve usability, personalize your experience, and improve our marketing. Privacy Policy.

By clicking "Accept" or further use of this website, you agree to allow cookies.

Accept
Learn Machine Learning by Doing Learn Now
You are reading solutions
alfie-grace-headshot-square2.jpg
Author: Alfie Grace
Data Scientist

Python Double Slash (//) Operator: Floor Division

In Python, we can perform floor division (also sometimes known as integer division) using the // operator. This operator will divide the first argument by the second and round the result down to the nearest whole number, making it equivalent to the math.floor() function.

See below for a quick example of this:

Which is the same as:

import math
math.floor(15 / 4)

/ vs // — division vs floor division

The result of regular division (using the / operator) is $\frac{15}{4} = 3.75$, but using // has floored $3.75$ down to $3$.

The result of regular division is always a float, whereas if one of the operands is a float in floor division, then the output will be a float.

The following shows an example of this:

print("Regular division")
print(2 / 2, "\tis a float.")

print("\nFloor division")
print(15 // 4, "\tis an int.")
print(15.0 // 4, "\tis a float.")
Out:
Regular division
1.0 	is a float.

Floor division
3 	is an int.
3.0 	is a float.

Floor division with negative numbers

When an operand is negative, floor division will return the largest integer less than or equal to the result of regular division. Let's use the same operands as before to show how this works:

print(15 / 4)
print(15 // 4)
print(-15 // 4)

Looking at the result of regular division when both numbers are positive, $\frac{15}{4}=3.75$, floor division returns $3$, since it's the largest integer less than or equal to $3.75$. When one of the operands is negative, the result of normal division is negative ($-3.75$), so the largest integer less than or equal is $-4$.

We'll look at where floor division may be helpful while also looking at other approaches that we could use to achieve similar results.

Floor division use cases

When using Python, you'll often see errors where functions are incompatible with floats. For example, let's say you wanted to use the range function with the quotient of two numbers:

for value in range(25 / 5):
    print(value)
Out:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-7584232b50b9> in <module>()
----> 1 for value in range(25 / 5):
      2     print(value)
TypeError: 'float' object cannot be interpreted as an integer

For our program to work correctly, we need to convert the quotient to an integer type first, which we can achieve with the // operator:

for value in range(25 // 5):
    print(value)

Another area you may want to use the floor operator is when indexing lists:

x = list(range(100))

x[len(x) / 10]
Out:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-28e5ba7c8efa> in <module>
      1 x = list(range(100))
      2 
----> 3 x[len(x) / 10]

TypeError: list indices must be integers or slices, not float

One way to resolve this would be to use the floor division operator:

Depending on your applications, flooring a number isn't necessarily the best option. In the next section, we'll look at various functions that can give a similar result.

Alternative approaches to //

Sometimes, you'll find yourself working with datasets that contain both integers and floats, for example, if you were using messy data.

In those circumstances, the // operator will produce inconsistent results, outputting both floats and integers. Thus, if your program is dependent on integers, then using the // operator will require extra steps to ensure a consistent output.

There are a few other ways to manipulate the quotient of two numbers to work appropriately with your program. For example, you may not always want to round a value down, so using different approaches can give you more control over the results.

Option 1: math.floor()

math.floor() achieves the same result as the floor division operator, rounding its argument down to the nearest integer.

One significant difference of using math.floor() is that it always outputs an integer, regardless of the input data type. When working with both integers and floats, math.floor() is more useful since it provides a more consistent output.

The following shows how we can floor the result of regular division:

import math
math.floor(15 / 4)

Like when using the floor operator, math.floor will still round down when the input is negative.

Option 2: math.ceil()

Alternatively to math.floor(), we can also use math.ceil(), which will always round up to the nearest whole number instead of down.

For example:

math.ceil(15 / 4)

In a similar way to math.floor, math.ceil always provides output as an integer-type, regardless of argument data types. math.ceil will round negative numbers up, so math.ceil(-15 / 4) would give -3 as a result.

Option 3: int()

For a quick fix, you can cast a float to an int. Passing a float to int() results in an integer where everything is cut off after the input float's decimal.

In the following example, $\frac{15}{4}=3.75$, but casting to an integer will chop off the $.75$:

int() works similarly to math.floor(), except int() effectively rounds negative numbers up instead of down:

print(math.floor(-15 / 4))
print(int(-15 / 4))

Option 4: round()

Alternatively to the math functions, we can also use round() for rounding values and then outputting the result as an integer.

The difference with round() is that it will use conventional rounding, i.e. that any decimal .5 and larger is rounded up.

The following demonstrates the usage of round():

We can also specify how many decimal points the input should be rounded.

The example below shows how we could round the result of 15 divided by 4 (3.75) to 1 decimal figure:

Adding a 1 after the comma communicates that we would like the result to have 1 decimal point, but we could use any number. For example, we could round the value of pi to nine decimal points:

round(math.pi, 9)

Summary

The floor division operator (//) is primarily used when you require an integer or need to return the smallest integer less than or equal to the input.

If the operands are both integers, then the output will an integer. If either operand is a float then the output will be a float.

Lines using the // operator are easy to read and idiomatic, but in cases where you're working with inconsistent and messy datasets, it may be better to use math.floor(), math.ceil(), int() or round().


Meet the Authors

alfie-grace-headshot-square2.jpg

Alfie graduated with a Master's degree in Mechanical Engineering from University College London. He's currently working as Data Scientist at Square Enix. Find him on LinkedIn.

Brendan Martin
Editor: Brendan
Founder of LearnDataSci

Get updates in your inbox

Join over 7,500 data science learners.