每天CookBook之Python-042

-精确的数字计算

a = 4.2
b = 2.1

print((a + b) == 6.3)

from decimal import Decimal

a = Decimal('4.2')
b = Decimal('2.1')

print (a + b) == Decimal('6.3')

from decimal import localcontext

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 = 50
    print (a / b)


nums = [1.23e+18, 1, -1.23e+18]

print(sum(nums))

import math

print(math.fsum(nums))

Out:

False
6.3
0.7647058823529411764705882353
0.765
0.76470588235294117647058823529411764705882352941176
0.0
1.0
posted @ 2016-07-18 23:52  4Thing  阅读(88)  评论(0编辑  收藏  举报