首页 > 解决方案 > 为什么 math.trunc 在 Python 中不能按预期工作?

问题描述

我尝试运行以下命令。我期待整数部分(151511919299292911851),但我得到的值是 151511919299292921856,比我预期的少 -10005。

import math
math.trunc(float('151511919299292911851.06'))

标签: pythonnumpymath

解决方案


这是由float值支持的有限精度(通常为 53 个有效位)引起的。Fraction为避免这种情况,请使用Pythonfractions模块中的任意精度类:


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

推荐阅读