Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Arithmetic operators: integer division

A // (double slash) sign is an integer divisional operator. It differs from the standard / operator in two details. 

  • its result lacks the fractional part- it's absent (for integers), or is always equal to zero (for floats); this means that the results are always rounded
  • it conforms to the integer vs. float rule. 

Run the example below and see the results:

print(6 // 3)

print(6 // 3.)

print(6. // 3)

print(6. // 3.)

As you can see, integer by integer division gives an integer result. All other cases produce floats. 

Let's do some more advanced tests. 

Look at the following snippet: 

print(6 // 4)

print(6. // 4)

Imagine that we used / instead of // - could you predict the results? 

Yes, it would be 1.5 in both cases. That's clear. 

But what results should we expect with the // division? 

Run the code and see for yourself. 

What we get is two ones - one integer and one float. 

The result of integer division is always rounded to the nearest integer value that is less than the real (not rounded) result.

This is very important: rounding always goes to the lesser integer. 

Look at the code below and try to predict the results once again: 

print(-6 // 4)

print(6. // -4)

Note: some of the values are negative. This will obviously affect the result. But how? 

The result is two negative twos. The real (not rounded) result is -1.5 in both cases. However, the results are the subjects of rounding. The rounding goes toward the lesser integer value, and the lesser integer value is -2, hence -2 and -2.0.

NOTE

Integer division can also be called floor division. You will definitely come across this term in the future. 

 

 

Arithmetic operators: integer division

David Khieu
Module by David Khieu, updated more than 1 year ago

Description

Arithmetic operators: integer division
No tags specified