Square root Python 2.7.12

后端 未结 4 1372
遥遥无期
遥遥无期 2021-01-22 01:29

Why does the math module return the wrong result?

First test

A = 12345678917
print \'A =\',A
B = sqrt(A**2)
print \'B =\',int(B)
         


        
4条回答
  •  星月不相逢
    2021-01-22 02:07

    The way floating-point numbers are stored in memory makes calculations with them prone to slight errors that can nevertheless be significant when exact results are needed. As mentioned in one of the comments, the decimal library can help you here:

    >>> A = Decimal(12345678917)
    >>> A
    Decimal('123456758365483459347856')
    >>> B = A.sqrt()**2
    >>> B
    Decimal('123456758365483459347856.0000')
    >>> A == B
    True
    >>> int(B)
    123456758365483459347856
    

    I use version 3.6, which has no hardcoded limit on the size of integers. I don't know if, in 2.7, casting B as an int would cause overflow, but decimal is incredibly useful regardless.

提交回复
热议问题