python 浮点数的精确计算

来源:互联网 发布:linux下载ed2k 编辑:程序博客网 时间:2024/06/06 09:02

在python 中浮点数的计算是会存在误差的,例如:

 a = 3.2 b = 2.1 print(a + b)

此段代码的结果是5.300000000000001,这种计算结果对于金融领域等要求精确而言,是不能容许的。
因此可以利用Decimal进行计算

from decimal import Decimal  a = Decimal('3.2')    b = Decimal('2.1')    print(a + b)

此时结果就是5.3

0 0