2014年03月31日 星期一 09:37
Python中的Decimal非常有意思,它最大的特点是:使用它来计算0.1+0.2会得到0.3。大家可能会问,这不很正常么? 大家可以用用Python内置的数据类型算一下0.1+0.2,结果应该是0.30000000000000004,呵呵。
Decimal号称:
computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.
示例代码如下:
from decimal import Decimal
a=Decimal('4.2')
b=Decimal('2.1')
print(a+b)
print(4.2+2.1)
print(a+b==Decimal('6.3'))
print(a+b==4.2+2.1)
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)
参考资料:
Zeuux © 2025
京ICP备05028076号