math module for Decimals

Mark Dickinson dickinsm at gmail.com
Sun Dec 28 11:24:02 EST 2008


On Dec 28, 3:55 pm, jerry.carl... at gmail.com wrote:
> But i am after the extra precision:
>
> >>> from math import *
> >>> (1+1e-16)-1
>
> 0.0

Sounds like you don't care too much about the base-10 part,
so there may be other solutions out there.

Have you tried:

1. mpmath?
2. sympy?
3. Sage?

Any of these is likely to be faster than a decimal
solution.

One thing that it would be *really* nice to have is a
set of Python bindings to MPFR---to me, MPFR is the
one obvious way to do high-precision math.  Maybe
bindings already exist somewhere.  Sage includes them, but
also includes many hundreds of megabytes of other stuff
that you probably don't need or want.

Maybe you could get access to MPFR via ctypes;  I don't
have any idea how feasible or complicated this might be.

> Sure, you can say, there is such a small market for this application,
> and maybe I should use other tools. Well, I found Python so much
> easier to use for other reasons. And, again, it seems like there is a
> desire for it outside of my own office.

Well, I'd certainly find high-precision sin, cos, ...
within Python useful.  I'd guess the market isn't *so* small.

> Agree: sin, cos and atan would do it.

I'll see if I can find time.  I've just discovered a half-finished
version of atan for Decimal sitting on my computer, complete with
error analysis.

> Wow, i would never think my posting would go that high in the Python
> world. I can't wait to tell my colleagues after these holidays ;-)

LOL---hardly!  I'm just one of hundreds of Python core devs, and I've
only been that for around a year...

> If I improve (in my view that is) the existing modules (dmath) etc. i
> will keep you posted. For now I am reducing large arguments of
> goniometric functions by adding the following into the dmath's sin(x)
> and cos(x):
>
> x=Decimal.__mod__(x,Decimal('2')*pi())
>
> Works fine for what i need, but i am sure it's not the right way to do
> it.

I don't know of any better way to deal with large arguments.
The main problem is that the reduction step can introduce fairly
large errors:  for example, if you're using a value of pi
that's accurate to 10**-20, say, then reducing something of
magnitude 10**5*pi will give a result with error of around
10**-15.  As far as I know, this problem is essentially
unavoidable, and it's the reason why implementing sin for inputs
like 10**999999999 isn't feasible.

Mark



More information about the Python-list mailing list