python中decimal用法详解

decimal是python内置库。

decimal模块支持快速正确四舍五入的十进制浮点运算。

示例代码:

import decimal

a = decimal.Decimal(123)
print(a)

b = decimal.Decimal(123456.123)
print(b)
print(a + b)

c = decimal.Decimal('123456.123')
print(a + c)

aa = 123
bb = 123456.123
print(aa + bb)

运行结果:

        与基于硬件的二进制浮点数不同,decimal 模块具有用户可更改的精度(默认为 28 位),对于给定问题,它可以根据需要设置为最大:

from decimal import getcontext, Decimal

getcontext().prec = 6
a = Decimal(1)
b = Decimal(7)
print(a)
print(b)
print(a / b)

getcontext().prec = 28
c = Decimal(1)
d = Decimal(7)
print(c)
print(d)
print(c / d)

运行结果:

        使用小数的通常开始是导入模块,查看当前上下文getcontext(),并在必要时为精度、舍入或启用的陷阱设置新值:

from decimal import getcontext

print(getcontext())
getcontext().prec = 6
print(getcontext())

运行结果:

        Decimal 实例可以从整数、字符串、浮点数或元组构造。从整数或浮点数构造执行该整数或浮点数的值的精确转换。十进制数包括特殊值,例如 NaN代表“不是数字”、正数和负数 Infinity,以及-0:

from decimal import getcontext, Decimal

getcontext().prec = 6
print(getcontext())
a = Decimal(10)
print(a, type(a))

b = Decimal(3.14)
print(b)

c = Decimal('3.14')
print(c)

d, e, f, g = Decimal((0, (3, 1, 4), -2)), Decimal((0, (3, 1, 4), -5)), Decimal((1, (3, 1, 4), -5)), Decimal((0, (3, 1, 4), 5))
print(d, e, f, g)

h = Decimal('NaN')
print(h, type(h))

i = Decimal('-Infinity')
print(i, type(i))

运行结果:

官方文档:decimal — Decimal fixed point and floating point arithmetic — Python 3.11.2 documentation

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年7月15日
下一篇 2023年7月15日

相关推荐