python - 为什么 math.trunc 在 Python 中不能按预期工作?
问题描述
我尝试运行以下命令。我期待整数部分(151511919299292911851),但我得到的值是 151511919299292921856,比我预期的少 -10005。
import math
math.trunc(float('151511919299292911851.06'))
解决方案
这是由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
推荐阅读
- vb.net - 带有完整事件的 vb6 上的 Show.net 控件
- doctrine - 教义数组集合过滤器性能
- javascript - 从 Extendscript Toolkit 中的 IconButton 中删除边框/轮廓
- c# - Intersect many list by one property
- typescript - 使用 TypeScript 时如何处理浏览器 API 中的可选参数
- kotlin - KafkaStreams:获取窗口最终结果
- c# - EF Db-first,EF 可以填充非实体属性吗?
- ios - 更改加载的 NSPersistentContainer
- php - 注意:只有变量应该通过引用传递
- flutter - Flutter center() 小部件所需参数错误