Python Decimal modf



获取python(python 3)Decimal的整数部分和小数部分的最有效方法是什么?

这就是我现在拥有的:

from decimal import *
>>> divmod(Decimal('1.0000000000000003')*7,Decimal(1))
(Decimal('7'), Decimal('2.1E-15'))

欢迎提出任何建议。

您也可以使用math.modf(文档)

>>> math.modf(1.0000000000000003)
(2.220446049250313e-16, 1.0)
python2.7 -m timeit -s 'import math' 'math.modf(1.0000000000000003)'
1000000 loops, best of 3: 0.191 usec per loop

divmod方法:

python2.7 -m timeit -s 'import decimal' 'divmod(decimal.Decimal(1.0000000000000003),decimal.Decimal(1))'
1000 loops, best of 3: 39.8 usec per loop

我认为math.modf 更有效

编辑

我想更简单有效的方法是将字符串转换为整数:

>>>a = int(Decimal('1.0000000000000003'))
1
>>>python2.7 -m timeit -s 'import decimal' 'int(decimal.Decimal('1.0000000000000003'))'
10000 loops, best of 3: 11.2 usec per loop

获取小数部分:

>>>int(Decimal('1.0000000000000003')) - a
3E-16
  • 整数部分
123.456 // 1
# 123.0
  • 小数部分
123.456 % 1
# 0.45600000000000307
  • 具有精度的小数部分
p = 3 # precision as 3
123.456 % 1 * (10**p // 1 / 10**p)
# 0.456
  • 自动检测精度
def modf(f):
    sf = str(f)
    i = sf.find(".")
    p  = len(sf)-i-1
    inter = f // 1
    fractional = f % 1 * 10**p // 1 / 10**p
    return inter,fractional
modf(123.456)
# (123, 0.456)

modf()math.modf()20微秒(1/1000000秒)

最新更新