问题描述
在编写python代码时,进行小数位相减时出现 TypeError: unsupported operand type(s) for -: ‘decimal.Decimal’ and ‘float’ 的错误提示信息
原因分析
以上导致报错的原因是,双精度类型和浮点型相减报错
Python 内置类浮点数执行计算时,我们会惊奇发现计算结果与我们想象的完全不一样,比如我们都知道1.1和2.2的总和是3.3,但在Python中却不是这样的。
>>> (1.1 + 2.2) == 3.3
False
>>> 1.1 + 2.2
3.3000000000000003
>>>
解决方法
为了解决这个问题,我们可以使用Python附带的十进制模块。浮点数的精度最多为 15 位小数,而小数点数模块的精度可由用户设置。
from decimal import Decimal
print(0.1)
print(decimal.Decimal(0.1))
输出结果
>>> from decimal import Decimal
>>> print(0.1)
0.1
>>> print(Decimal(0.1))
0.1000000000000000055511151231257827021181583404541015625
>>>
修改python代码,如下所示:
# yx_jxxs = (jxxs - 1.1) / (0.15 * 12) // TypeError: unsupported operand type(s) for -: 'decimal.Decimal' and 'float'
yx_jxxs = (jxxs - Decimal("1.1")) / Decimal(str(0.15*12))
运行代码,错误解决