Python Division: Floor, Ceil & Remainder Made Simple

目次

1. Introduction

1-1. Basics of Division in Python

In Python, there are several ways to perform division. Primarily, there are three types, each with different result formats and use cases.
  1. Standard division (/)
  • The result is a floating-point number (float)
  • Example: 10 / 33.3333333333333335
  1. Floor division (//)
  • It yields an integer result by discarding the fractional part
  • Example: 10 // 33
  1. Modulo division (%)
  • It calculates the remainder of a division
  • Example: 10 % 31
Understanding these operations and using them appropriately is important for numeric processing in Python.

1-2. Ways to Get an Integer Result from Division

1-2-1. Using // (floor division)

Floor division (//) discards the fractional part and returns only the integer portion.
print(10 // 3)  # output: 3
print(-10 // 3) # output: -4  (floored toward negative)

1-2-2. Using int()

You can also explicitly convert the result of standard division (/) to an integer using int().
print(int(10 / 3))  # output: 3
However, int() truncates toward zero, so you need to be careful when handling negative numbers.

1-3. Difference Between Truncation and Rounding

When converting division results to integers, it’s also important to understand the difference between truncation and rounding.
  • Truncation: Unconditionally discards the fractional part (e.g., 3.93)
  • Rounding: Rounds considering the fractional part (e.g., 3.54)
In Python, you can perform rounding using round().
print(round(3.5))  # output: 4
print(round(3.4))  # output: 3

1-4. What You’ll Learn in This Article

In this article, we will explain the basic concepts of division in Python, with a particular focus on floor division. In the upcoming sections, we will deepen practical knowledge by providing concrete code examples and cautions.

2. Python Division: The Basic / Operator

2-1. / (slash) Operator Basics

When you use / in Python, the result is always a floating-point number (float). This is also true for division between integers.

Example: Regular Division

print(10 / 3)  # Output: 3.3333333333333335
print(8 / 2)   # Output: 4.0
print(5 / 2)   # Output: 2.5
Thus, the calculation result is of type float, preserving the fractional part.

2-2. Differences Between int and float Types

When using Python’s / operator, the result is a float even if the inputs are of type int.

Example: Calculation Involving Integers

a = 10
b = 2
c = a / b
print(c)           # Output: 5.0
print(type(c))     # Output: <class 'float'>
In this code, a and b are integers (int), but the result of a / b is the float 5.0.

2-3. How to Get an Integer Result When Needed

2-3-1. Using // (floor division)

Using // yields an integer result with the fractional part truncated.
print(10 // 3)  # Output: 3
print(8 // 2)   # Output: 4

2-3-2. Explicitly Converting to Integer with int()

Applying int() after a regular / operation truncates the fractional part, yielding an integer.
print(int(10 / 3))  # Output: 3
However, be careful when handling negative numbers.

2-4. Considerations When Using / for Calculations

2-4-1. Dividing by 0 Raises an Error

In Python, division by zero raises a ZeroDivisionError, causing the program to halt.
print(10 / 0)  # ZeroDivisionError: division by zero
Mitigation: A common way to prevent division by zero is to check with an if statement beforehand.
a, b = 10, 0
if b != 0:
    print(a / b)
else:
    print("Cannot divide by zero")

2-4-2. Calculations with Negative Numbers

Dividing a negative number by / returns a float result according to standard mathematical rules.
print(-10 / 3)  # Output: -3.3333333333333335
print(10 / -3)  # Output: -3.3333333333333335
When calculating with negative numbers, you need to handle truncation or rounding appropriately.

2-5. Uses and Summary of the / Operator

  • Using / always yields a float result
  • If you want an integer result, use // or int()
  • Division by 0 raises an error, so it must be handled appropriately
  • Be mindful of results when dealing with negative numbers</>
年収訴求

3. Python Truncating Division (Floor Division / Integer Conversion)

3-1. Basics of // (Floor Division)

// can be used to obtain the result of a division as an integer by discarding the fractional part.

Example: Floor Division

print(10 // 3)  # Output: 3
print(8 // 2)   # Output: 4
print(5 // 2)   # Output: 2
Unlike the regular / (slash) operator, using // yields a result that is an integer (int).
print(10 / 3)   # Output: 3.3333333333333335
print(10 // 3)  # Output: 3
As such, // ignores the fractional part and returns only the integer portion.

3-2. Differences from int()

You can also achieve integer conversion by using int() instead of //, but there are differences.

When using int()

By using the regular / to obtain a floating-point result and then applying int(), you can convert it to an integer.
print(int(10 / 3))  # Output: 3

Differences from //

int()</ truncates the fractional part, but because the calculation involves a float intermediate, // is more efficient in terms of speed.
print(type(10 // 3))  # Output: <class 'int'>
print(type(int(10 / 3)))  # Output: <class 'int'>
Although they appear similar, int() first converts the result of / to a float before truncating, so using // directly is preferable.

3-3. Beware of Truncating Negative Numbers (-10 // 3 Behavior)

When calculating with negative numbers using //, the result follows the mathematical floor function (rounding down), which can produce unintuitive outcomes.

Example: Floor Division with Negative Numbers

print(-10 // 3)  # Output: -4
In standard mathematics, -10 ÷ 3 = -3.333..., which might suggest -3, but Python’s // always rounds toward the smaller (more negative) direction, resulting in -4.

Comparing Positive and Negative Numbers

print(10 // 3)   # Output: 3
print(-10 // 3)  # Output: -4
Because this behaves as “apply floor() (round down) to the division result,” extra care is needed when dealing with negative numbers.

3-4. Differences from math.floor()

Python provides a math.floor() function that also discards the fractional part.

Basics of math.floor()

import math
print(math.floor(10 / 3))  # Output: 3
print(math.floor(-10 / 3)) # Output: -4
math.floor() behaves like // by rounding down the fractional part, but its return value is a float.
print(type(10 // 3))  # Output: <class 'int'>
print(type(math.floor(10 / 3)))  # Output: <class 'float'>
Understanding this difference and choosing the appropriate method is important.

3-5. Uses and Summary of the // Operator

Using Python’s // (floor division) yields an integer value by discarding the fractional part. It is especially useful in the following scenarios.
  • When only an integer result is needed
  • Example: calculating the total number of pages for pagination
  items = 45
  per_page = 10
  total_pages = (items + per_page - 1) // per_page
  print(total_pages)  # Output: 5
  • When handling negative numbers requires caution
  • // always rounds toward the smaller (more negative) direction, so you should verify that it yields the intended result for negative numbers.
  • When you want to quickly process calculations that don’t need decimals
  • int(10 / 3) is slower than 10 // 3.

4. Python Ceiling Division (math.ceil())

4-1. Basics of math.ceil()

Python’s math.ceil() is a function that unconditionally rounds up the fractional part and returns an integer. This function is included in the math module, so you need to import math when using it.

Example: Using math.ceil()

import math

print(math.ceil(10 / 3))  # Output: 4
print(math.ceil(5 / 2))   # Output: 3
print(math.ceil(4.2))     # Output: 5
In this way, math.ceil() rounds up the fractional part completely to an integer.

4-2. Difference between math.ceil() and // (floor division)

Since ceiling and floor operations are opposite, it’s important to understand the difference between them.

Floor division (//)

print(10 // 3)  # Output: 3
print(-10 // 3) # Output: -4
  • // truncates the fractional part (negative numbers go toward the smaller direction)
  • Be careful with results for negative numbers

Ceiling (math.ceil())

import math
print(math.ceil(10 / 3))  # Output: 4
print(math.ceil(-10 / 3)) # Output: -3
  • math.ceil() rounds up the fractional part
  • For negative numbers, it rounds toward the larger direction

4-3. Practical examples using math.ceil()

4-3-1. Calculating number of pages

For example, when dividing data into pages, taking into account the number of items per page, you need to round up the page count even if there is a remainder.
import math

items = 45   # total number of items
per_page = 10  # number of items per page

total_pages = math.ceil(items / per_page)
print(total_pages)  # Output: 5

4-3-2. Calculating required number of work assignments

For example, suppose 100 tasks are processed by 5 people. When calculating the number of tasks each person should handle, if there is a remainder, you need to process one extra.
import math

tasks = 100   # total number of tasks
workers = 6   # number of workers

tasks_per_worker = math.ceil(tasks / workers)
print(tasks_per_worker)  # Output: 17

4-4. How to achieve ceiling without using math.ceil()

math.ceil() can be avoided by using integer division to achieve ceiling. This is the following ‘integer arithmetic using addition and subtraction‘.

Using (a + b – 1) // b

This method adds (b - 1) to the dividend a and divides by b, achieving a ceiling effect.
def ceil_div(a, b):
    return (a + b - 1) // b

print(ceil_div(10, 3))  # Output: 4
print(ceil_div(5, 2))   # Output: 3

4-5. Uses and summary of math.ceil()

Python’s math.ceil() is useful when you need to round up the fractional part to get an integer. It is especially effective in situations such as:
  • When calculating the number of pages or groups
  import math
  items = 45
  per_page = 10
  total_pages = math.ceil(items / per_page)
  print(total_pages)  # Output: 5
  • When you want to increase the number of processing rounds even if there is a remainder
  import math
  tasks = 100
  workers = 6
  tasks_per_worker = math.ceil(tasks / workers)
  print(tasks_per_worker)  # Output: 17
  • When you want to perform ceiling division using only integers
  def ceil_div(a, b):
      return (a + b - 1) // b
  print(ceil_div(10, 3))  # Output: 4

5. How to Get Quotient and Remainder Simultaneously

5-1. Calculating Remainder Using % (Modulo Operator)

In Python, the basic way to obtain a remainder is to use the % (modulo operator).

Example: Remainder Calculation

print(10 % 3)  # Output: 1
print(20 % 7)  # Output: 6
a % b returns the remainder of a divided by b. For example, with 10 % 3, 10 ÷ 3 = 3 ... 1, so the remainder 1 is produced.

Be Careful with Remainders of Negative Numbers

The Python % operator is affected by the sign of the dividend (the number being divided), so you need to be careful when dealing with negative numbers.
print(-10 % 3)  # Output: 2
print(10 % -3)  # Output: -2
This is because the Python % operator follows the rule of returning a remainder with the same sign as the divisor (the number you divide by).

5-2. Using divmod() to Retrieve Quotient and Remainder Simultaneously

Using Python’s divmod() function, you can obtain both the quotient and remainder in a single calculation.

Basics of divmod()

quotient, remainder = divmod(10, 3)
print(quotient)  # Output: 3
print(remainder) # Output: 1
In this code, divmod(10, 3) returns the tuple (3, 1), which is unpacked into quotient (the quotient) and remainder (the remainder).

When Negative Numbers Are Involved

divmod() also follows Python’s rules, just like the % operator.
print(divmod(-10, 3))  # Output: (-4, 2)
print(divmod(10, -3))  # Output: (-4, -2)
Thus, the quotient behaves like //, and the remainder matches the result of %.

5-3. Comparison When Using // and % Separately

divmod(a, b) computes a // b and a % b simultaneously, but let’s review the differences compared to using // and % separately.

Method Using Two Calculations

a = 10
b = 3
quotient = a // b
remainder = a % b

print(quotient)  # Output: 3
print(remainder) # Output: 1
This method also obtains the quotient and remainder, but it requires two separate calculations.

Method Using divmod()

quotient, remainder = divmod(10, 3)
print(quotient)  # Output: 3
print(remainder) # Output: 1
With this approach, a single function call retrieves both values, making the number of calculations fewer and more efficient.

5-4. Practical Examples of divmod()

5-4-1. Converting to Hours and Minutes

For example, to split a total of 145 minutes into hours and minutes, you can easily calculate it using divmod().
minutes = 145
hours, remainder_minutes = divmod(minutes, 60)

print(f"{hours} hours {remainder_minutes} minutes")  # Output: 2 hours 25 minutes

5-4-2. Coin Calculation

By leveraging divmod(), you can easily calculate how to break an amount into specific coin denominations.
amount = 758  # 758 yen
yen_100, remainder = divmod(amount, 100)  # number of 100-yen coins
yen_50, remainder = divmod(remainder, 50)  # number of 50-yen coins
yen_10, remainder = divmod(remainder, 10)  # number of 10-yen coins

print(f"100 yen: {yen_100} coins, 50 yen: {yen_50} coins, 10 yen: {yen_10} coins, remainder: {remainder} yen")

5-5. Summary of Division and Remainder Calculation Methods

When calculating quotients and remainders in Python, it’s important to choose the method appropriate to the use case.
MethodUsageQuotientRemainder
//a // b×
%a % b×
divmod()divmod(a, b)
In particular, divmod() can retrieve both the quotient and remainder at once, reducing repeated calculations and allowing you to write more efficient code.

6. Frequently Asked Questions (FAQ) about Division in Python

6-1. How to make division results integers in Python?

There are three main ways to get integer results from division in Python.

① Use // (floor division)

// yields an integer result with the fractional part truncated.
print(10 // 3)  # Output: 3
print(-10 // 3) # Output: -4

② Use int()

You can also explicitly convert the result of a regular division (/) to an integer using int().
print(int(10 / 3))  # Output: 3
However, because int() truncates the fractional part, its behavior with negative numbers can differ from that of //.

③ Use math.floor()

Using Python’s math.floor() function converts to an integer by always rounding down.
import math
print(math.floor(10 / 3))  # Output: 3
print(math.floor(-10 / 3)) # Output: -4

6-2. What is the difference between truncation and rounding?

  • Truncation (floor division): Use // or math.floor()
  • Rounding: Use round()

Example: Rounding

print(round(3.5))  # Output: 4
print(round(3.4))  # Output: 3
Python’s round() follows the banker’s rounding (round-to-even) rule, so round(2.5) yields 2 and round(3.5) yields 4.

6-3. What is the difference between int() and math.floor()?

MethodBehaviorHandling of negative numbersReturn type
int()Truncates the fractional partint(-3.9) → -3int
math.floor()Always rounds downmath.floor(-3.9) → -4float
Because they handle negative numbers differently, it is important to understand the differences int() and math.floor() and use them appropriately.

6-4. What should you watch out for when truncating negative numbers?

Python’s // (floor division) is defined to truncate toward the negative direction.
print(-10 // 3)  # Output: -4
Because it follows the mathematical floor function, you need to be careful when truncating negative numbers.

6-5. How to round to a specific number of decimal places?

Using Python’s round(), you can round to a specified number of decimal places.
print(round(3.14159, 2))  # Output: 3.14
print(round(3.14159, 3))  # Output: 3.142

6-6. What happens when dividing by zero?

In Python, dividing by zero raises a ZeroDivisionError.
print(10 / 0)  # ZeroDivisionError: division by zero
To prevent this error, you need to check for zero beforehand.
a, b = 10, 0
if b != 0:
    print(a / b)
else:
    print("Cannot divide by zero")

6-7. What are the benefits of divmod()?

Using Python’s divmod() function lets you obtain the quotient and remainder simultaneously, reducing the number of calculations and enabling more efficient code.
quotient, remainder = divmod(10, 3)
print(quotient)  # Output: 3
print(remainder) # Output: 1

6-8. How to perform accurate floating-point calculations in Python?

Because Python’s floating-point numbers suffer from rounding errors, you should use the decimal module when precision is required.
from decimal import Decimal

a = Decimal('10.1')
b = Decimal('3.3')
print(a / b)  # Accurate calculation possible

6-9. How to format division results as strings in Python?

If you want to format division results as strings, you can use f-strings or format().
result = 10 / 3
print(f"{result:.2f}")  # Output: 3.33
print("{:.2f}".format(result))  # Output: 3.33

7. Summary

7-1. How to Choose the Best Method for Each Situation

Python offers various ways to perform division, and it’s important to choose the method that best fits the situation.
SituationRecommended MethodDescription
Accurate calculation including fractional part/Standard division (floating-point)
Want an integer result (floor)//Floor division (result as integer type)
Want an integer result (truncate decimal part)int()Convert float to int (be careful with negative numbers)
Want to round upmath.ceil()Use math.ceil() to round up
Want to get the remainder%Obtain only the remainder
Want to get both quotient and remainder simultaneouslydivmod()Get quotient and remainder at once
Want to avoid floating-point errorsdecimal.DecimalHigh-precision calculation

7-2. Points to Note When Dealing with Division

When performing division in Python, you need to be aware of several important points.

1. // (floor division) behaves differently with negative numbers

// (floor division) rounds toward the smaller direction, which can produce results that differ from intuition when dealing with negative numbers.
print(-10 // 3)  # Output: -4
Understanding this behavior, it may be appropriate to use math.floor() in some cases.

2. Division by zero raises an error

In Python, dividing by zero raises a ZeroDivisionError, so you need to check beforehand.
a, b = 10, 0
if b != 0:
    print(a / b)
else:
    print("Cannot divide by zero")

3. round() performs bankers rounding (round to even)

Python’s round() follows the bankers rounding (round to even) rule, so round(2.5) yields 2 and round(3.5) yields 4.
print(round(2.5))  # Output: 2
print(round(3.5))  # Output: 4

4. divmod() can make calculations more efficient

Using divmod() reduces the number of calculations compared to computing the quotient and remainder separately, allowing for more efficient code.
quotient, remainder = divmod(10, 3)
print(quotient)  # Output: 3
print(remainder) # Output: 1

7-3. Summary of This Article

Python offers many ways to perform division, each suited to different use cases. Summarizing the content covered in this article, we have the following:
  1. Standard division (/) returns a result of type float.
  2. If you want an integer result, use // (floor division).
  3. When dealing with negative numbers, be aware of //‘s behavior (it truncates toward the negative direction).
  4. Use round() for rounding to the nearest integer.
  5. Use math.ceil() to round up, and math.floor() to round down.
  6. Use % to get the remainder, and divmod() to obtain both quotient and remainder simultaneously.
  7. If high precision is required, use decimal.Decimal.
If you can use division in Python properly, you can handle data processing and calculations more flexibly and accurately. This concludes the article. Have you deepened your understanding of Python’s division and become able to choose the appropriate method? If you have questions, refer to the official Python documentation or try writing code yourself. Continue learning to make Python programming even more comfortable in the future!
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール