Search code examples
pythonpython-3.xmathdivisioninteger-division

Python3 Stop division for large floats


I am dividing extremely large integers, so to speak up to 1kb integers and I ran into 2 problems already. Either

OverflowError: integer division result too large for a float

or The float is rounded off to some digits and when I try to multiply back I get a slightly different number.

Is there any way in python to somehow prevent from dividing floats that have more than 20 digits after the decimal point?

smallest_floats = []

n1 = int(input())
n2 = int(input())

while n2 != 1:
  smallest_floats.append(str(n1/n2))
     n2 -= 1
print(min(smallest_floats, key=len))

I am thinking that the possible solutions is to somehow assert division or:

len(s.split(".")[-1]) > 20

Solution

  • For rational number arithmetic without precision loss you can use the fractions.Fraction class from the fractions package. You can divide by another rational number and then multiply by it again in order to obtain the very same rational number you had at the beginning.

    >>> from fractions import Fraction
    >>> n1 = Fraction(large_numerator, denominator)
    >>> n2 = n1 / some_rational_number
    >>> assert n1 == n2 * some_rational_number