Search code examples
pythonintegerlong-integerlargenumberfloor

Python Math.floor not producing correct values with large ints


I'm currently having some issues with the math.floor() function in python. I am attempting to compute the following value:

math.floor((3710402416420168191+3710402416420167681)/2)

This is producing the answer

3710402416420167680

Which I know is not right. I think this has something to do with Python's ability to do arithmetic with very large numbers -- can anyone help out?

Thanks!


Solution

  • Avoid using floating point numbers. Python only uses 53 bits of precision for floating point numbers, but integers can grow arbitrarily large:

    >>> int((3710402416420168191 + 3710402416420167681) / 2)
    3710402416420167680
    >>> (3710402416420168191 + 3710402416420167681) // 2
    3710402416420167936
    

    // is floor division, so it'll return the integral part of the result without resorting to floats (which is what math.floor returns).