Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage division of huge numbers in Python?

I have a 100 digit number and I am trying to put all the digits of the number into a list, so that I can perform operations on them. To do this, I am using the following code:

for x in range (0, 1000):
   list[x] = number % 10
   number = number / 10

But the problem I am facing is that I am getting an overflow error something like too large number float/integer. I even tried using following alternative

number = int (number / 10)

How can I divide this huge number with the result back in integer type, that is no floats?

like image 352
Ambidextrous Avatar asked Jan 14 '15 15:01

Ambidextrous


People also ask

How do you deal with large numbers in Python?

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.

How does Python handle division?

In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.

How do you program a division in Python?

Floor Division and True Division In Python 3. x, slash operator ("/") does true division for all types including integers, and therefore, e.g. 3/2==1.5. The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0.

How do you fix integer division results too large for a float?

The Python "OverflowError: integer division result too large for a float" occurs when the result of a division is too large. Use the floor division // operator to solve the error, e.g. result = large_num // 5 .


1 Answers

In Python 3, number / 10 will try to return a float. However, floating point values can't be of arbitrarily large size in Python and if number is large an OverflowError will be raised.

You can find the maximum that Python floating point values can take on your system using the sys module:

>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308

To get around this limitation, instead use // to get an integer back from the division of the two integers:

number // 10

This will return the int floor value of number / 10 (it does not produce a float). Unlike floats, int values can be as large as you need them to be in Python 3 (within memory limits).

You can now divide the large numbers. For instance, in Python 3:

>>> 2**3000 / 10
OverflowError: integer division result too large for a float

>>> 2**3000 // 10
123023192216111717693155881327...
like image 153
Alex Riley Avatar answered Sep 21 '22 03:09

Alex Riley