Setting longer default decimal precision
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Nov 18 09:43:34 EST 2013
On Mon, 18 Nov 2013 14:14:33 +0000, Kay Y. Jheallee wrote:
> Using 1/3 as an example,
[snip examples]
> which seems to mean real (at least default) decimal precision is limited
> to "double", 16 digit precision (with rounding error).
That's because Python floats actually are implemented as C doubles. And
no, they're not configurable.
However, Python also has a Decimal class, which (unlike floats) are
actually decimal rather than binary, and include configurable precision.
There is a performance hit -- prior to Python version 3.3, Decimal was
quite slow, but in 3.3 they got a major speed increase and are now nearly
as fast as floats.
An example:
py> import decimal
py> x = decimal.Decimal(1)/3
py> decimal.getcontext().prec = 50
py> y = decimal.Decimal(1)/3
py> print(x, y)
0.3333333333333333333333333333
0.33333333333333333333333333333333333333333333333333
--
Steven
More information about the Python-list
mailing list