python cookbook 3.2 执行精确的浮点数运算

python cookbook 3.2 执行精确的浮点数运算

#这是由于浮点数底层的误差引起的。可以使用decimal模块来计算
from decimal import localcontext,Decimal
a=Decimal('1.3')
b=Decimal('1.7')
print(a/b)
with localcontext() as ctx:
    ctx.prec=3
    print(a/b)
with localcontext() as ctx:
    ctx.prec=40   #保留小数点后40位
    print(a/b)

python cookbook 3.2 执行精确的浮点数运算

#有些错误仍然难以避免
nums=[1.23e+18,1,-1.23e+18]
print(sum(nums))

python cookbook 3.2 执行精确的浮点数运算

#上面错误可以利用math.fsum()提供的更精确计算能力来解决:
import math
print(math.fsum(nums))

python cookbook 3.2 执行精确的浮点数运算