不仅手机上的python会出现这样的问题,其他平台上也会出现:
- >>> 1.2 + 1.2 + 1.2 - 3.6
- -4.440892098500626e-16
- >>> 1.1 + 2.2
- 3.3000000000000003
- >>> 1.0 - 1.0001
- -9.999999999998899e-05
复制代码究其原因,
其他更多关于二进制小数可参考知乎回答
- https://zhihu.com/question/25457573/answer/30851062
复制代码那么怎么去解决:
Python 官方文档中文翻译版:http://python.usyiyi.cn/documents/python_352/library/decimal.html#module-decimal
总之,二进制小数在计算机里面的存储是「不准确」的,可能有误差,可能拖很多9或者0,所以一般不强求默认的浮点数做到精度计算。
但如果一定要高精度计算,用「十进制小数」模块decimal,下面是官方给出的例子:
- >>> from decimal import *
- >>> getcontext().prec = 6
- >>> Decimal(1) / Decimal(7)
- Decimal('0.142857')
- >>> getcontext().prec = 28
- >>> Decimal('0.1428571428571428571428571429')
- Decimal('0.1428571428571428571428571429')
复制代码