Search code examples
pythonoverflowlargenumber

Multiply Very Large Numbers Accurately in Python


I am trying to multiply very large floats by very large integers in Python and am noticing small inaccuracies. For example:

a = 45310630.0
b = 1023473145

c = int(a * b)
print(c)

The answer I am getting is 46374212988031352 but I know the answer should be 46374212988031350. When I change variable "a" to an integer, the multiplication is performed correctly. However, since "a" comes from a division (and might not be a whole number), I can't simply convert it to an integer.


Solution

  • If you use fractions.Fraction you can handle larger numbers accurately, at the cost of some efficiency:

    from fractions import Fraction
    a = Fraction(45310630.0)
    b = Fraction(1023473145)
    
    c = int(a * b)
    print(c)
    

    Output:

    46374212988031350
    

    Some timings:

    In [2]: a = Fraction(45310630.0)
       ...: b = Fraction(1023473145)
       ...:
    
    In [3]: %timeit int(a * b)
    3.92 µs ± 21.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    In [4]: a = 45310630.0
       ...: b = 1023473145
       ...:
    
    In [5]: %timeit int(a * b)
    479 ns ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)