Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #67226

Re: extend methods of decimal module

From Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de>
Subject Re: extend methods of decimal module
Date 2014-02-28 14:41 +0000
Newsgroups comp.lang.python
Message-ID <mailman.7472.1393598536.18130.python-list@python.org> (permalink)

Show all headers | View raw


Mark H. Harris <harrismh777 <at> gmail.com> writes:
> 
> If you get a chance, take a look at the  dmath.py  code on:
> 
>    https://code.google.com/p/pythondecimallibrary/ 
> 

Hi Mark,
here is an enhancement for your epx function.
Your current version comes with the disadvantage of potentially storing
extremely large values in n and d because of the multiplications in the
while loop:

    q = D(x)
    n = q
    c = D(1)
    d = D(1)
    ex = 1 + q
    prev_ex = D(0)
    while (ex != prev_ex):
        prev_ex = ex
        c += 1
        d *= c    # can become a huge number
        n *= q    # this as well
        ex += n/d

in general, large numbers are handled well by the Decimal class, but there
is a certain burden on these calculations and with VERY large numbers you
can also get a decimal.Overflow:

>>> exp(200000)
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    epx(190000)
  File "C:\Python34\dmath_rev.py", line 27, in epx
    n *= q
decimal.Overflow: [<class 'decimal.Overflow'>]

My re-write of the part above is:

    q = D(x)
    c = 1
    new_element = q
    ex = 1 + new_element
    prev_ex = D(0)
    while (ex != prev_ex):
        prev_ex = ex
        c += 1
        # every new element in the series is a known fraction of the
        # previous element,
        # so there is no need to store large numbers
        new_element *= q/c
        ex += new_element

in my hands, this simple change increases performance (exact timing left to
you) and boost the range of possible calculations:

>>> epx2(1000000)
Decimal('3.033215396802087545086402141E+434294')

Cheers,
Wolfgang

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: extend methods of decimal module Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> - 2014-02-28 14:41 +0000
  Re: extend methods of decimal module Wolfgang <xpysol@gmail.com> - 2014-02-28 06:52 -0800
  Re: extend methods of decimal module "Mark H. Harris" <harrismh777@gmail.com> - 2014-02-28 10:17 -0800

csiph-web