gpt4 book ai didi

Python 十进制 modf

转载 作者:行者123 更新时间:2023-11-28 18:47:52 27 4
gpt4 key购买 nike

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

这是我现在拥有的:

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

欢迎提出任何建议。

最佳答案

您还可以使用 math.modf ( Documentation )

>>> 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

关于Python 十进制 modf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com