我尝试运行以下命令。我期待的是整数部分(151511919299292911851),但我得到的值是151511919299292921856,比我预期的少-10005。
import math
math.trunc(float('151511919299292911851.06'))
这是由float
值支持的有限精度(通常为53位有效位)引起的。为了避免这种情况,请使用Python的fractions
模块中的任意精度Fraction
类:
In [32]: from fractions import Fraction
In [35]: import math
In [38]: math.trunc(Fraction('151511919299292911851.06'))
Out[38]: 151511919299292911851
In [39]: math.trunc(float('151511919299292911851.06'))
Out[39]: 151511919299292921856
In [40]: math.trunc(float('-151511919299292911851.06'))
Out[40]: -151511919299292921856
In [41]: math.trunc(Fraction('-151511919299292911851.06'))
Out[41]: -151511919299292911851