floating point – How to manage division of huge numbers in Python?

floating point – How to manage division of huge numbers in Python?

In Python 3, number / 10 will try to return a float. However, floating point values cant 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...

If you have an integer and you want each digit in a list, you can use:

>>> map(int,list(str(number)))
[1, 5, 0, 3, 0, 0, 7, 6, 4, 2, 2, 6, 8, 3, 9, 7, 5, 0, 3, 6, 6, 4, 0, 5, 1, 2, 4, 3, 7, 8, 2, 5, 2, 4, 4, 5, 4, 8, 4, 0, 6, 6, 4, 5, 0, 9, 2, 4, 8, 9, 2, 9, 7, 8, 7, 3, 9, 9, 9, 7, 0, 1, 7, 4, 8, 2, 4, 4, 2, 9, 6, 9, 5, 1, 7, 1, 3, 4, 8, 5, 1, 3, 3, 1, 7, 9, 0, 1, 0, 1, 9, 3, 8, 4, 2, 0, 1, 9, 2, 9]

it transform the int into a string, then list will take each character of the string and put it in a list. Finally, map will convert each item of the list into an int again

floating point – How to manage division of huge numbers in Python?

Python will automatically handle large ints of arbitrary length. What it wont do is handle floats of arbitrary length so you need to make sure youre not getting floats along the way.

Leave a Reply

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