Division in Python Programming Language

In Python, Division of numbers can be done in two ways. One way being True Division and other being Floor Division.

True Division – Denoted by symbol(/) it divides number on left side by right side and returns a floating point number. For example – 12/3 will return 4.0.
• Floor Division – Denoted by symbol(//) it divides number on left side by right side and returns a floored value(Nearest lower whole number) of division result. For example – 10//3 will return 3 instead of 3.33. As division result 3.33 is floored to nearest lower whole number.

How to divide numbers in Python?

For dividing two numbers in Python you can use either true or floor division.
Below is a table listing how to do division(true or floor) in Python with examples.

# declare two numbers num1 and num2
num1 = 28
num2 = 38

# True Division
result1 = num1/num2  # Will returns 0.7368421052631579

# Floor Division
result2 = num1//num2   # Will return 0

Just a point, I would like to highlight here is that if you want result to not roundoff then use True Division, otherwise if you does want result to round off then using Floor Division is best option.

Keeping Precision while dividing in Python?

As you see above either of True or Floor devision is doing truncation to results of division. But what if you want to have some precision in division result let’s say you want result to be precise upto 10 decimals. How to do this? How to get precise division result?
For getting precision in division result, you need to use decimal module in python and need to set How much precision you want? before doing division.
Below code example explains this.

from decimal import *       # Importing decimal python module
getcontext().prec = 20      # Setting up how much precise result need to be
Decimal(10)/Decimal(3)      # Doing True Division
# Returns Decimal('3.3333333333333333333')

Note that this method of obtaining precise result up to certain decimal of precision works only for True Division and not for Floor Division as it inherently have a step of flooring result to nearest whole number.

Josh

Hi, I'm Josh a Computer Science graduate from California State University, Sacramento since coming out with my Master's from university. I've worked with multiple startups across US and in UK as well primarily as a Python Developer. Here on this website, I'm sharing my knowledge of Python. If you want to ask me anything about Python feel free to reach out, I would be happy to help you out.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts