Why are the results of integer division and converting to an int after division different for large numbers?

前端 未结 1 1321
谎友^
谎友^ 2020-12-21 15:24
print(10**40//2)
print(int(10**40/2))

Output of the codes:

5000000000000000000000000000000000000000
5000000000000000151893014213501         


        
相关标签:
1条回答
  • 2020-12-21 15:54

    The floating point representation of 10**40//2 is not accurate:

    >>> format(float(10**40//2), '.0f')
    '5000000000000000151893014213501833445376'
    

    That's because floating point arithmetic is only ever an approximation, especially when you go beyond what your CPU can accurately model (as floating point is handled in hardware).

    The integer division never has to represent the 10**40 number as a float, it only has to divide the integer, which in Python can be arbitrarily large without precision loss.

    Also see:

    • Floating Point Arithmetic: Issues and Limitations in the Python tutorial
    • What Every Programmer Should Know About Floating-Point Arithmetic
    • What Every Computer Scientist Should Know About Floating-Point Arithmetic

    Also look at the decimal module if you must use higher-precision floating point arithmetic.

    0 讨论(0)
提交回复
热议问题