为什么是数学?trunc在Python中不像预期的那样工作?



我尝试运行以下命令。我期待的是整数部分(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

最新更新