1. 浮点数精度问题
问题
由于二进制浮点数(float)的存储方式,某些十进制小数无法精确表示,导致计算误差:
示例1:
print(0.1 + 0.2) # 输出 0.30000000000000004,而不是 0.3
print(1.1 + 2.2) # 输出 3.3000000000000003
示例2:
(26.06 - 26.05) >= 0.01 # 输出False
解决方案
-
方法 1:使用
round()四舍五入(但不完全可靠)print(round(0.1 + 0.2, 1)) # 0.3 -
方法 2:使用
decimal模块(适合金融计算)from decimal import Decimal print(Decimal("0.1") + Decimal("0.2")) # 精确输出 0.3 -
方法 3:使用
math.isclose()比较浮点数import math print(math.isclose(0.1 + 0.2, 0.3)) # True
2.round() 的银行家舍入法
问题
Python 的 round() 采用“四舍六入五成双”规则,可能导致意外结果:
print(round(2.5)) # 2(舍入到最近的偶数)
print(round(3.5)) # 4
解决方案
-
如果需要传统“四舍五入”,可以手动实现:
def classic_round(x): return int(x + 0.5) if x >= 0 else int(x - 0.5) print(classic_round(2.5)) # 3
2466

被折叠的 条评论
为什么被折叠?



