[Python-Dev] Decimal FAQ
raymond.hettinger at verizon.net
Mon May 23 04:13:36 CEST 2005
Some of the private email I've received indicates a need for a decimal
FAQ that would shorten the module's learning curve.
A discussion draft follows.
Q. It is cumbersome to type decimal.Decimal('1234.5'). Is there a way
minimize typing when using the interactive interpreter?
A. Some users prefer to abbreviate the constructor to just a single
>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Q. I'm writing a fixed-point application to two decimal places.
Some inputs have many places and needed to be rounded. Others
are not supposed to have excess digits and need to be validated.
What methods should I use?
A. The quantize() method rounds to a fixed number of decimal
places. If the Inexact trap is set, it is also useful for
>>> TWOPLACES = Decimal(10) ** -2
>>> # Round to two places
>>> # Validate that a number does not exceed two places
Q. Once I have valid two place inputs, how do I maintain that invariant
throughout an application?
A. Some operations like addition and subtraction automatically
preserve fixed point. Others, like multiplication and division,
change the number of decimal places and need to be followed-up with
a quantize() step.
Q. There are many ways to write express the same value. The numbers
200, 200.000, 2E2, and .02E+4 all have the same value at various
Is there a way to transform these to a single recognizable canonical
A. The normalize() method maps all equivalent values to a single
>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
Q. Is there a way to convert a regular float to a Decimal?
A. Yes, all binary floating point numbers can be exactly expressed as a
Decimal. An exact conversion may take more precision than intuition
suggest, so trapping Inexact will signal a need for more precision:
"Convert a floating point number to a Decimal with no loss of
# Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0)
# exponent. Double the mantissa until it is an integer. Use the
# mantissa and exponent to compute an equivalent Decimal. If this
# be done exactly, then retry with more precision.
mantissa, exponent = math.frexp(f)
while mantissa != int(mantissa):
mantissa *= 2
exponent -= 1
mantissa = int(mantissa)
oldcontext = getcontext()
return mantissa * Decimal(2) ** exponent
getcontext().prec += 1
Q. Why isn't the floatToDecimal() routine included in the module?
A. There is some question about whether it is advisable to mix binary
decimal floating point. Also, its use requires some care to avoid the
representation issues associated with binary floating point:
Q. I have a complex calculation. How can I make sure that I haven't
a spurious result because of insufficient precision or rounding
A. The decimal module makes it easy to test results. A best practice
to re-run calculations using greater precision and with various rounding
modes. Widely differing results indicate insufficient precision,
mode issues, ill-conditioned inputs, or a numerically unstable
Q. I noticed that context precision is applied to the results of
but not to the inputs. Is there anything I should watch out for when
values of different precisions?
A. Yes. The principle is all values are considered to be exact and so
the arithmetic on those values. Only the results are rounded. The
for inputs is that "what you type is what you get". A disadvantage is
the results can look odd if you forget that the inputs haven't been
>>> getcontext().prec = 3
>>> Decimal('3.104') + D('2.104')
>>> Decimal('3.104') + D('0.000') + D('2.104')
The solution is either to increase precision or to force rounding of
using the unary plus operation:
>>> getcontext().prec = 3
Alternatively, inputs can be rounded upon creation using the
>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Q. I'm writing an application that tracks measurement units along
with numeric values (for example 1.1 meters and 2.3 grams). Is a
Decimal subclass the best approach?
A. Like other numeric types, Decimal objects are dimensionless and
all of its methods are designed around this concept. To add dimension,
a Decimal subclass would likely need to override every method. For
example, without an overriding the __add__() method in a Measurement
subclass of Decimal, a calculation like "MeasurementA + MeasurementB"
would return a dimensionless Decimal object instead of another
Measurement object -- the units would be lost.
A simple alternative is to construct record tuples such as
"meters"). This allows direct use of existing decimal methods:
if a == b: return (a+b, a).
A more versatile approach is to create a separate class with Decimal
objects as attributes (working in a "has-a" capacity rather than an
"is-a" capacity) and then delegating the arithmetic to the Decimal
More information about the Python-Dev