simonzack
simonzack

Reputation: 20928

Python Decimal modf

What's the most efficient way to get the integer part and fractional part of a python (python 3) Decimal?

This is what I have right now:

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

Any suggestions are welcome.

Upvotes: 4

Views: 1091

Answers (2)

ZenG
ZenG

Reputation: 169

  • integer part
123.456 // 1
# 123.0
  • fractional part
123.456 % 1
# 0.45600000000000307
  • fractional part with precision
p = 3 # precision as 3
123.456 % 1 * (10**p // 1 / 10**p)
# 0.456
  • automatically detect precision
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() is 20 microseconds(1/1000000 seconds) slower than math.modf()

Upvotes: 2

user1786283
user1786283

Reputation:

You can also use 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

The divmod method:

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

I believe the more efficient is math.modf

Edit

I guess even more simpler and efficient way is to just convert the string to an integer:

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

To get the decimal part:

>>>int(Decimal('1.0000000000000003')) - a
3E-16

Upvotes: 2

Related Questions