
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Divide Large Numbers Using Python
Python allows you to perform the basic mathematical operations like addition, subtraction, multiplication, and division on large numbers as Python's integers are arbitrary-precision, hence there is no limit on their size.
- You can divide large numbers as you would normally do. But this has a lot of precision issues as such operations cannot be guaranteed to be precise, as it might slow down the language.
- Usually, dividing large numbers results in a floating-point number, which cannot be precise since Python's float can only accurately be represented up to 15-17 decimal digits.
- To overcome this issue, we can perform division operation using division operator (/), floor division operator, or decimal module.
Let us discuss each approach in detail with the help of examples -
Divide Large Numbers Using Division Operator
Two larger numbers can be divided using either the division operator (/) or the floor division operator (//). The division operator returns a float result, while the floor division operator (//) returns the largest integer less than or equal to the result (i.e., it performs integer division).
Example
In the example program below, we will use the basic division operator / (which gives float output) and // operator (which gives integer output):
a = 81434917259440465804 b = 12345678901234567890 # Floating-point division res = a / b # Integer division res_int = a // b print("Float division:", res) print("Integer division:", res_int)
The output of the above code is as follows -
Float division: 6.596228357380733 Integer division: 6
Divide Large Numbers Using Decimal Module
The Decimal module provides support to return correctly rounded decimal floating-point arithmetic. You can use this module along with the getcontext() method to perform a division operation on a large number.
Example
The example program uses a decimal module to return a high-precision decimal value as output:
from decimal import Decimal, getcontext getcontext().prec = 10 # set a precision a = Decimal(81434917259440465804) b = Decimal(12345678901234567890) res = a / b print("The quotient after diving two large numbers is equal to:", res)
The output of the above code is as follows -
The quotient after diving two large numbers is equal to: 6.596228357