Setting longer default decimal precision

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Nov 20 09:02:20 EST 2013


Hi Kay,

You emailed me off-list, but your email address is bouncing or invalid, 
so I have no way to email you back.

Unless you have something private or personal to say, you should keep 
replies on the list here so that others can either answer your questions 
or learn from the responses. If you do have something private to say, you 
should use a real email address that accepts replies :-)

I'm taking the liberty of republishing your comments to me here:

[you wrote]
Okay,but after I import "math" and "decimal",

py> decimal.getcontext().prec=75
py> print decimal.Decimal(math.atan(1))
0.78539816339744827899949086713604629039764404296875

though I set precision to 75, it only did the trig function to 50
places AND it is only right to 16 places,

0.785398163397448309615660845819875721049292349843776...(actual).
[end quote]


Here, you calculate the atan of 1 using floating point maths, that is, to 
the precision of C doubles (about 17 decimal places). After the 
calculation is performed using float, you then convert it to a Decimal, 
but it is too late, you can't retroactively regain precision.

In a perfect world, this would work:

math.atan(Decimal(1))

but alas, all the functions in the math module convert their arguments to 
float first, so even though your Decimal(1) could perform calculations to 
75 decimal places, the math.atan function downgrades it to a regular 
float.

Unfortunately, Decimals don't support high-precision trig functions. If 
you study the decimal.py module, you could possibly work out how to add 
support for trig functions, but they have no current support for them.

You could try this third-party module:

http://code.google.com/p/mpmath/‎

which claims to be arbitrary-precision maths for Python, but I've never 
used it.


-- 
Steven



More information about the Python-list mailing list