Definition
The decimal module is the module of the Python §12.23 standard library for decimal floating-point arithmetic. Its class Decimal stores a number as a sign, an integer coefficient and a power of ten, so decimals such as 0.1 are stored exactly. Each arithmetic result is rounded to a set number of significant digits. A context object sets that number, the rounding rule, and which exceptional conditions raise errors. The module follows the General Decimal Arithmetic Specification published by IBM (International Business Machines) [391].
The idea
An invoicing program adds an amount of 0.10 to an amount of 0.20. With Python’s built-in float type, a binary floating-point §4.49 number, the sum prints as 0.30000000000000004, because neither 0.10 nor 0.20 can be written exactly in base two; an auditor adding the same figures by hand gets 0.30. With the decimal module, Decimal('0.10') + Decimal('0.20') equals Decimal('0.30') exactly, because the numbers are kept in base ten, the base in which people wrote them.
Changing the base removes one kind of rounding, not all of it. A finite string of decimal digits can hold one tenth but not one third: has infinitely many decimal digits, just as one tenth has infinitely many binary digits. Every operation whose exact result needs more digits than the program allows must still round. What the module adds is control and visibility: the program chooses how many digits to keep and how to round, and the module records every time it rounded. A ruler marked in millimeters is a fair picture: it has a mark at exactly 12.3 cm, which a ruler marked in sixteenths of an inch does not, yet it has no mark at one third of 10 cm. The picture stops in one respect: a Decimal can keep more digits on request, but no finite number of digits reaches one third.
How it works
Values. A Decimal is , where the sign is 0 or 1, the coefficient is a non-negative integer and the exponent is an integer. Decimal('1.30') has and . Trailing zeros are kept, so Decimal('1.30') equals Decimal('1.3') in value but prints differently. There are also infinities, negative zero, and NaN (not a number), the result of an invalid operation such as zero divided by zero when that condition is set not to raise an exception.
Construction is exact. A new Decimal keeps every digit of its input, whatever the precision setting described below. Decimal('0.1') is one tenth. Decimal(0.1), built from a float, is that float’s exact binary value written in decimal, with 55 digits after the point:
0.1000000000000000055511151231257827021181583404541015625
The context. Every operation takes its rules from the current context, which getcontext() returns. Each thread has its own current context, and localcontext() changes the rules for one block of code only. The main settings are these.
prec, the precision: the number of significant digits each result keeps, 28 by default. Significant digits are counted from the first non-zero digit, wherever the decimal point falls. Precision here means a count of digits, not the statistical sense of precision versus accuracy §11.34.rounding: one of eight rounding modes. The default,ROUND_HALF_EVEN, rounds to the nearest value and sends an exact half to the neighbor whose last digit is even, so rounding to whole numbers turns 2.5 into 2 and 3.5 into 4.ROUND_HALF_UPsends halves away from zero, as taught in school, so 2.5 becomes 3.trapsandflags. The module calls each exceptional condition a signal, a word unrelated to operating-system signals. A flag records that a signal occurred and stays set until the program clears it; a trap, if enabled, turns the signal into an exception. By defaultInvalidOperation,DivisionByZeroandOverfloware trapped, whileInexact, meaning that a result was rounded and changed in value, only sets its flag.
Each operation rounds once. An arithmetic operation computes the exact result, rounds it to prec significant digits with the context’s rounding mode, then sets flags and raises an exception for any trapped signal. Addition rounds too when the exact sum has more than prec digits. To round to a fixed number of places instead, as for cents, x.quantize(Decimal('0.01')) rounds to two digits after the point.
Mixing with binary floats. An arithmetic operation between a Decimal and a float raises TypeError, so a binary value cannot enter a calculation unnoticed through an operator. Integers mix freely and are treated exactly.
Worked example
Division at a precision of 3 digits. Set prec to 3 and keep the default rounding mode.
Decimal(1) / Decimal(3): the exact quotient is . Keeping 3 significant digits gives0.333, and the context sets theInexactflag.Multiplying by 3 gives , which has 3 significant digits, so this step is exact.
The result differs from 1 by . The multiplication made no error; it carried forward the error that the division made.
Significant digits, not places. In the same context, Decimal(100000) / Decimal(3) gives 3.33E+4, that is , although the exact quotient is . Even addition rounds: has 4 significant digits, so the stored sum is 1.00.
Dividing money. Under the default context, divide 100.00 into three equal shares. Decimal('100.00') / 3 is 33.33333333333333333333333333, which has 28 significant digits. Rounding to cents with quantize(Decimal('0.01')) gives 33.33 for each share. The three shares add up to , so is unaccounted for. Every step was computed correctly. The missing cent is a rounding remainder, and the application must assign it by a stated rule, for example by adding it to the first share, which becomes 33.34.
Stated precisely
Let be the context precision, and let be the exact mathematical result of adding, subtracting, multiplying or dividing two finite Decimal values. Assume that the result’s exponent stays within the context’s limits, which are to by default. Then the module returns , the value rounded to significant digits by the context’s rounding mode. If can be written with at most significant digits, . Otherwise , and the Inexact flag is set.
For , let be the integer with , so that the last digit kept is worth . With a round-to-nearest mode, such as the default ROUND_HALF_EVEN, For , the relative error of one operation is therefore at most . With a directed mode, one that always rounds in the same direction, such as ROUND_DOWN toward zero, both bounds double.
These bounds hold per operation, and errors from successive operations can add up, as the worked example shows. The flags give an exact test: if the Inexact flag is clear before a calculation and still clear after it, and no other code used the same context in between, no operation in the calculation rounded. Enabling the trap for Inexact makes the first rounding raise an exception instead. Construction from a string or an integer is always exact; construction from a float reproduces the float’s binary value exactly.
Limits and common mistakes
Values with infinitely many decimal digits, such as or , are always rounded. The fractions module §15.25 keeps such values exactly, as ratios of integers.
Precision counts significant digits, so large values lose small parts. With the default 28 digits, Decimal(10**30) + Decimal('0.01') returns 1.000000000000000000000000000E+30: the exact sum has 33 significant digits, 31 before the point and 2 after, and the 0.01 is lost.
A Decimal built from a float carries the float’s binary error. Decimal(2.675) is
2.67499999999999982236431605997495353221893310546875
so rounding it to two places gives 2.67, whereas Decimal('2.675') rounds to 2.68 under the default mode. Build values from strings.
The rounding mode must match the rule the application has to follow. Rounding 7.325 to cents gives 7.32 under the default ROUND_HALF_EVEN but 7.33 under ROUND_HALF_UP, the rule many people expect. Tax and accounting rules state their own rounding, so select the mode explicitly.
The context belongs to the thread. A precision or rounding mode set in one thread does not apply in another, so set the context in the thread where the calculation runs, or pass a context object explicitly.
Exact arithmetic does not make data accurate. A voltage reading of 3.217 V from an instrument accurate to 0.05 V is not improved by storing it exactly; the module controls arithmetic error, not measurement error.
Questions answered
Does using decimal eliminate all rounding error?
No, using Python’s decimal module does not eliminate all rounding error. The module removes one source of rounding error, the conversion of decimal inputs such as 0.1 into binary, but each arithmetic result is still rounded to a fixed number of significant digits, 28 by default. A result that needs more digits, such as , is rounded, and later exact steps carry the error forward: at a precision of 3 digits, gives 0.333, and , not 1. Very large values lose their small digits, a Decimal built from a binary float carries the float’s error, and splitting an amount into rounded shares leaves a remainder, such as the cent left over when 100.00 is split into three shares of 33.33.
What the module provides is control and detection. The program chooses the precision and the rounding mode, rounds to a fixed number of places with quantize, and can detect any rounding through the Inexact flag, which the module sets whenever a result is rounded, or turn the first rounding into an exception by trapping Inexact.
Related entries: fractions module (§15.25), Resolution versus precision versus accuracy (§11.34), Calibration (§11.42), Binary floating-point representation, special values, and rounding (§4.49). Further reading: [143, 391].