Python 中 int 和 float 的精度问题
Python 中 float 的精度问题是如何产生的?如何精确进行十进制运算?Decimal 的用法是什么?
回答
苦行僧
float 精度问题:二进制无法精确表示大部分十进制小数。
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 * 3) # 0.30000000000000004
解决方案:使用 decimal.Decimal
from decimal import Decimal, getcontext
# 默认精度 28 位
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 0.3 精确
# 设置精度
getcontext().prec = 6
print(Decimal('1') / Decimal('7')) # 0.142857
# 财务计算推荐
price = Decimal('19.99')
tax = Decimal('0.08')
total = price * (Decimal('1') + tax)
print(total) # 21.5892
选择建议:
- 普通计算:float 足够
- 金融/货币:Decimal
- 科学计算:考虑使用
fractions.Fraction或第三方库
注意:Decimal 性能比 float 慢很多。