| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 |  | 
| Raymond Hettinger | 13a7075 | 2008-02-10 07:21:09 +0000 | [diff] [blame] | 2 | :mod:`decimal` --- Decimal fixed point and floating point arithmetic | 
|  | 3 | ==================================================================== | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 4 |  | 
|  | 5 | .. module:: decimal | 
|  | 6 | :synopsis: Implementation of the General Decimal Arithmetic  Specification. | 
|  | 7 |  | 
|  | 8 |  | 
|  | 9 | .. moduleauthor:: Eric Price <eprice at tjhsst.edu> | 
|  | 10 | .. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar> | 
|  | 11 | .. moduleauthor:: Raymond Hettinger <python at rcn.com> | 
|  | 12 | .. moduleauthor:: Aahz <aahz at pobox.com> | 
|  | 13 | .. moduleauthor:: Tim Peters <tim.one at comcast.net> | 
|  | 14 |  | 
|  | 15 |  | 
|  | 16 | .. sectionauthor:: Raymond D. Hettinger <python at rcn.com> | 
|  | 17 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 18 | .. versionadded:: 2.4 | 
|  | 19 |  | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 20 | .. import modules for testing inline doctests with the Sphinx doctest builder | 
| Georg Brandl | 17baef0 | 2008-03-22 10:56:23 +0000 | [diff] [blame] | 21 | .. testsetup:: * | 
|  | 22 |  | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 23 | import decimal | 
|  | 24 | import math | 
| Georg Brandl | 17baef0 | 2008-03-22 10:56:23 +0000 | [diff] [blame] | 25 | from decimal import * | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 26 | # make sure each group gets a fresh context | 
|  | 27 | setcontext(Context()) | 
| Georg Brandl | 17baef0 | 2008-03-22 10:56:23 +0000 | [diff] [blame] | 28 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 29 | The :mod:`decimal` module provides support for decimal floating point | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 30 | arithmetic.  It offers several advantages over the :class:`float` datatype: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 31 |  | 
| Raymond Hettinger | 13a7075 | 2008-02-10 07:21:09 +0000 | [diff] [blame] | 32 | * Decimal "is based on a floating-point model which was designed with people | 
|  | 33 | in mind, and necessarily has a paramount guiding principle -- computers must | 
|  | 34 | provide an arithmetic that works in the same way as the arithmetic that | 
|  | 35 | people learn at school." -- excerpt from the decimal arithmetic specification. | 
|  | 36 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 37 | * Decimal numbers can be represented exactly.  In contrast, numbers like | 
|  | 38 | :const:`1.1` do not have an exact representation in binary floating point. End | 
|  | 39 | users typically would not expect :const:`1.1` to display as | 
|  | 40 | :const:`1.1000000000000001` as it does with binary floating point. | 
|  | 41 |  | 
|  | 42 | * The exactness carries over into arithmetic.  In decimal floating point, ``0.1 | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 43 | + 0.1 + 0.1 - 0.3`` is exactly equal to zero.  In binary floating point, the result | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 44 | is :const:`5.5511151231257827e-017`.  While near to zero, the differences | 
|  | 45 | prevent reliable equality testing and differences can accumulate. For this | 
| Raymond Hettinger | 13a7075 | 2008-02-10 07:21:09 +0000 | [diff] [blame] | 46 | reason, decimal is preferred in accounting applications which have strict | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 47 | equality invariants. | 
|  | 48 |  | 
|  | 49 | * The decimal module incorporates a notion of significant places so that ``1.30 | 
|  | 50 | + 1.20`` is :const:`2.50`.  The trailing zero is kept to indicate significance. | 
|  | 51 | This is the customary presentation for monetary applications. For | 
|  | 52 | multiplication, the "schoolbook" approach uses all the figures in the | 
|  | 53 | multiplicands.  For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 * | 
|  | 54 | 1.20`` gives :const:`1.5600`. | 
|  | 55 |  | 
|  | 56 | * Unlike hardware based binary floating point, the decimal module has a user | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 57 | alterable precision (defaulting to 28 places) which can be as large as needed for | 
| Georg Brandl | 17baef0 | 2008-03-22 10:56:23 +0000 | [diff] [blame] | 58 | a given problem: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 59 |  | 
|  | 60 | >>> getcontext().prec = 6 | 
|  | 61 | >>> Decimal(1) / Decimal(7) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 62 | Decimal('0.142857') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 63 | >>> getcontext().prec = 28 | 
|  | 64 | >>> Decimal(1) / Decimal(7) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 65 | Decimal('0.1428571428571428571428571429') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 66 |  | 
|  | 67 | * Both binary and decimal floating point are implemented in terms of published | 
|  | 68 | standards.  While the built-in float type exposes only a modest portion of its | 
|  | 69 | capabilities, the decimal module exposes all required parts of the standard. | 
|  | 70 | When needed, the programmer has full control over rounding and signal handling. | 
| Raymond Hettinger | 13a7075 | 2008-02-10 07:21:09 +0000 | [diff] [blame] | 71 | This includes an option to enforce exact arithmetic by using exceptions | 
|  | 72 | to block any inexact operations. | 
|  | 73 |  | 
|  | 74 | * The decimal module was designed to support "without prejudice, both exact | 
|  | 75 | unrounded decimal arithmetic (sometimes called fixed-point arithmetic) | 
|  | 76 | and rounded floating-point arithmetic."  -- excerpt from the decimal | 
|  | 77 | arithmetic specification. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 78 |  | 
|  | 79 | The module design is centered around three concepts:  the decimal number, the | 
|  | 80 | context for arithmetic, and signals. | 
|  | 81 |  | 
|  | 82 | A decimal number is immutable.  It has a sign, coefficient digits, and an | 
|  | 83 | exponent.  To preserve significance, the coefficient digits do not truncate | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 84 | trailing zeros.  Decimals also include special values such as | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 85 | :const:`Infinity`, :const:`-Infinity`, and :const:`NaN`.  The standard also | 
|  | 86 | differentiates :const:`-0` from :const:`+0`. | 
|  | 87 |  | 
|  | 88 | The context for arithmetic is an environment specifying precision, rounding | 
|  | 89 | rules, limits on exponents, flags indicating the results of operations, and trap | 
|  | 90 | enablers which determine whether signals are treated as exceptions.  Rounding | 
|  | 91 | options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`, | 
|  | 92 | :const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 93 | :const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 94 |  | 
|  | 95 | Signals are groups of exceptional conditions arising during the course of | 
|  | 96 | computation.  Depending on the needs of the application, signals may be ignored, | 
|  | 97 | considered as informational, or treated as exceptions. The signals in the | 
|  | 98 | decimal module are: :const:`Clamped`, :const:`InvalidOperation`, | 
|  | 99 | :const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`, | 
|  | 100 | :const:`Overflow`, and :const:`Underflow`. | 
|  | 101 |  | 
|  | 102 | For each signal there is a flag and a trap enabler.  When a signal is | 
|  | 103 | encountered, its flag is incremented from zero and, then, if the trap enabler is | 
|  | 104 | set to one, an exception is raised.  Flags are sticky, so the user needs to | 
|  | 105 | reset them before monitoring a calculation. | 
|  | 106 |  | 
|  | 107 |  | 
|  | 108 | .. seealso:: | 
|  | 109 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 110 | * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic | 
|  | 111 | Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 112 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 113 | * IEEE standard 854-1987, `Unofficial IEEE 854 Text | 
| Mark Dickinson | ff6672f | 2008-02-07 01:14:23 +0000 | [diff] [blame] | 114 | <http://754r.ucbtest.org/standards/854.pdf>`_. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 115 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 116 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 117 |  | 
|  | 118 |  | 
|  | 119 | .. _decimal-tutorial: | 
|  | 120 |  | 
|  | 121 | Quick-start Tutorial | 
|  | 122 | -------------------- | 
|  | 123 |  | 
|  | 124 | The usual start to using decimals is importing the module, viewing the current | 
|  | 125 | context with :func:`getcontext` and, if necessary, setting new values for | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 126 | precision, rounding, or enabled traps:: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 127 |  | 
|  | 128 | >>> from decimal import * | 
|  | 129 | >>> getcontext() | 
|  | 130 | Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 131 | capitals=1, flags=[], traps=[Overflow, DivisionByZero, | 
|  | 132 | InvalidOperation]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 133 |  | 
|  | 134 | >>> getcontext().prec = 7       # Set a new precision | 
|  | 135 |  | 
|  | 136 | Decimal instances can be constructed from integers, strings, or tuples.  To | 
|  | 137 | create a Decimal from a :class:`float`, first convert it to a string.  This | 
|  | 138 | serves as an explicit reminder of the details of the conversion (including | 
|  | 139 | representation error).  Decimal numbers include special values such as | 
|  | 140 | :const:`NaN` which stands for "Not a number", positive and negative | 
| Georg Brandl | 17baef0 | 2008-03-22 10:56:23 +0000 | [diff] [blame] | 141 | :const:`Infinity`, and :const:`-0`. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 142 |  | 
|  | 143 | >>> Decimal(10) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 144 | Decimal('10') | 
|  | 145 | >>> Decimal('3.14') | 
|  | 146 | Decimal('3.14') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 147 | >>> Decimal((0, (3, 1, 4), -2)) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 148 | Decimal('3.14') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 149 | >>> Decimal(str(2.0 ** 0.5)) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 150 | Decimal('1.41421356237') | 
|  | 151 | >>> Decimal(2) ** Decimal('0.5') | 
|  | 152 | Decimal('1.414213562373095048801688724') | 
|  | 153 | >>> Decimal('NaN') | 
|  | 154 | Decimal('NaN') | 
|  | 155 | >>> Decimal('-Infinity') | 
|  | 156 | Decimal('-Infinity') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 157 |  | 
|  | 158 | The significance of a new Decimal is determined solely by the number of digits | 
|  | 159 | input.  Context precision and rounding only come into play during arithmetic | 
| Georg Brandl | 17baef0 | 2008-03-22 10:56:23 +0000 | [diff] [blame] | 160 | operations. | 
|  | 161 |  | 
|  | 162 | .. doctest:: newcontext | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 163 |  | 
|  | 164 | >>> getcontext().prec = 6 | 
|  | 165 | >>> Decimal('3.0') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 166 | Decimal('3.0') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 167 | >>> Decimal('3.1415926535') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 168 | Decimal('3.1415926535') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 169 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 170 | Decimal('5.85987') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 171 | >>> getcontext().rounding = ROUND_UP | 
|  | 172 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 173 | Decimal('5.85988') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 174 |  | 
|  | 175 | Decimals interact well with much of the rest of Python.  Here is a small decimal | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 176 | floating point flying circus: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 177 |  | 
| Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 178 | .. doctest:: | 
|  | 179 | :options: +NORMALIZE_WHITESPACE | 
|  | 180 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 181 | >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()) | 
|  | 182 | >>> max(data) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 183 | Decimal('9.25') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 184 | >>> min(data) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 185 | Decimal('0.03') | 
| Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 186 | >>> sorted(data) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 187 | [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'), | 
|  | 188 | Decimal('2.35'), Decimal('3.45'), Decimal('9.25')] | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 189 | >>> sum(data) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 190 | Decimal('19.29') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 191 | >>> a,b,c = data[:3] | 
|  | 192 | >>> str(a) | 
|  | 193 | '1.34' | 
|  | 194 | >>> float(a) | 
|  | 195 | 1.3400000000000001 | 
|  | 196 | >>> round(a, 1)     # round() first converts to binary floating point | 
|  | 197 | 1.3 | 
|  | 198 | >>> int(a) | 
|  | 199 | 1 | 
|  | 200 | >>> a * 5 | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 201 | Decimal('6.70') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 202 | >>> a * b | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 203 | Decimal('2.5058') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 204 | >>> c % a | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 205 | Decimal('0.77') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 206 |  | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 207 | And some mathematical functions are also available to Decimal: | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 208 |  | 
|  | 209 | >>> Decimal(2).sqrt() | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 210 | Decimal('1.414213562373095048801688724') | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 211 | >>> Decimal(1).exp() | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 212 | Decimal('2.718281828459045235360287471') | 
|  | 213 | >>> Decimal('10').ln() | 
|  | 214 | Decimal('2.302585092994045684017991455') | 
|  | 215 | >>> Decimal('10').log10() | 
|  | 216 | Decimal('1') | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 217 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 218 | The :meth:`quantize` method rounds a number to a fixed exponent.  This method is | 
|  | 219 | useful for monetary applications that often round results to a fixed number of | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 220 | places: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 221 |  | 
|  | 222 | >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 223 | Decimal('7.32') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 224 | >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 225 | Decimal('8') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 226 |  | 
|  | 227 | As shown above, the :func:`getcontext` function accesses the current context and | 
|  | 228 | allows the settings to be changed.  This approach meets the needs of most | 
|  | 229 | applications. | 
|  | 230 |  | 
|  | 231 | For more advanced work, it may be useful to create alternate contexts using the | 
|  | 232 | Context() constructor.  To make an alternate active, use the :func:`setcontext` | 
|  | 233 | function. | 
|  | 234 |  | 
|  | 235 | In accordance with the standard, the :mod:`Decimal` module provides two ready to | 
|  | 236 | use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The | 
|  | 237 | former is especially useful for debugging because many of the traps are | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 238 | enabled: | 
|  | 239 |  | 
|  | 240 | .. doctest:: newcontext | 
|  | 241 | :options: +NORMALIZE_WHITESPACE | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 242 |  | 
|  | 243 | >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) | 
|  | 244 | >>> setcontext(myothercontext) | 
|  | 245 | >>> Decimal(1) / Decimal(7) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 246 | Decimal('0.142857142857142857142857142857142857142857142857142857142857') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 247 |  | 
|  | 248 | >>> ExtendedContext | 
|  | 249 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, | 
|  | 250 | capitals=1, flags=[], traps=[]) | 
|  | 251 | >>> setcontext(ExtendedContext) | 
|  | 252 | >>> Decimal(1) / Decimal(7) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 253 | Decimal('0.142857143') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 254 | >>> Decimal(42) / Decimal(0) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 255 | Decimal('Infinity') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 256 |  | 
|  | 257 | >>> setcontext(BasicContext) | 
|  | 258 | >>> Decimal(42) / Decimal(0) | 
|  | 259 | Traceback (most recent call last): | 
|  | 260 | File "<pyshell#143>", line 1, in -toplevel- | 
|  | 261 | Decimal(42) / Decimal(0) | 
|  | 262 | DivisionByZero: x / 0 | 
|  | 263 |  | 
|  | 264 | Contexts also have signal flags for monitoring exceptional conditions | 
|  | 265 | encountered during computations.  The flags remain set until explicitly cleared, | 
|  | 266 | so it is best to clear the flags before each set of monitored computations by | 
|  | 267 | using the :meth:`clear_flags` method. :: | 
|  | 268 |  | 
|  | 269 | >>> setcontext(ExtendedContext) | 
|  | 270 | >>> getcontext().clear_flags() | 
|  | 271 | >>> Decimal(355) / Decimal(113) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 272 | Decimal('3.14159292') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 273 | >>> getcontext() | 
|  | 274 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 275 | capitals=1, flags=[Rounded, Inexact], traps=[]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 276 |  | 
|  | 277 | The *flags* entry shows that the rational approximation to :const:`Pi` was | 
|  | 278 | rounded (digits beyond the context precision were thrown away) and that the | 
|  | 279 | result is inexact (some of the discarded digits were non-zero). | 
|  | 280 |  | 
|  | 281 | Individual traps are set using the dictionary in the :attr:`traps` field of a | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 282 | context: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 283 |  | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 284 | .. doctest:: newcontext | 
|  | 285 |  | 
|  | 286 | >>> setcontext(ExtendedContext) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 287 | >>> Decimal(1) / Decimal(0) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 288 | Decimal('Infinity') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 289 | >>> getcontext().traps[DivisionByZero] = 1 | 
|  | 290 | >>> Decimal(1) / Decimal(0) | 
|  | 291 | Traceback (most recent call last): | 
|  | 292 | File "<pyshell#112>", line 1, in -toplevel- | 
|  | 293 | Decimal(1) / Decimal(0) | 
|  | 294 | DivisionByZero: x / 0 | 
|  | 295 |  | 
|  | 296 | Most programs adjust the current context only once, at the beginning of the | 
|  | 297 | program.  And, in many applications, data is converted to :class:`Decimal` with | 
|  | 298 | a single cast inside a loop.  With context set and decimals created, the bulk of | 
|  | 299 | the program manipulates the data no differently than with other Python numeric | 
|  | 300 | types. | 
|  | 301 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 302 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 303 |  | 
|  | 304 |  | 
|  | 305 | .. _decimal-decimal: | 
|  | 306 |  | 
|  | 307 | Decimal objects | 
|  | 308 | --------------- | 
|  | 309 |  | 
|  | 310 |  | 
|  | 311 | .. class:: Decimal([value [, context]]) | 
|  | 312 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 313 | Construct a new :class:`Decimal` object based from *value*. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 314 |  | 
| Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 315 | *value* can be an integer, string, tuple, or another :class:`Decimal` | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 316 | object. If no *value* is given, returns ``Decimal('0')``.  If *value* is a | 
| Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 317 | string, it should conform to the decimal numeric string syntax after leading | 
|  | 318 | and trailing whitespace characters are removed:: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 319 |  | 
|  | 320 | sign           ::=  '+' | '-' | 
|  | 321 | digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 
|  | 322 | indicator      ::=  'e' | 'E' | 
|  | 323 | digits         ::=  digit [digit]... | 
|  | 324 | decimal-part   ::=  digits '.' [digits] | ['.'] digits | 
|  | 325 | exponent-part  ::=  indicator [sign] digits | 
|  | 326 | infinity       ::=  'Infinity' | 'Inf' | 
|  | 327 | nan            ::=  'NaN' [digits] | 'sNaN' [digits] | 
|  | 328 | numeric-value  ::=  decimal-part [exponent-part] | infinity | 
|  | 329 | numeric-string ::=  [sign] numeric-value | [sign] nan | 
|  | 330 |  | 
|  | 331 | If *value* is a :class:`tuple`, it should have three components, a sign | 
|  | 332 | (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of | 
|  | 333 | digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))`` | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 334 | returns ``Decimal('1.414')``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 335 |  | 
|  | 336 | The *context* precision does not affect how many digits are stored. That is | 
|  | 337 | determined exclusively by the number of digits in *value*. For example, | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 338 | ``Decimal('3.00000')`` records all five zeros even if the context precision is | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 339 | only three. | 
|  | 340 |  | 
|  | 341 | The purpose of the *context* argument is determining what to do if *value* is a | 
|  | 342 | malformed string.  If the context traps :const:`InvalidOperation`, an exception | 
|  | 343 | is raised; otherwise, the constructor returns a new Decimal with the value of | 
|  | 344 | :const:`NaN`. | 
|  | 345 |  | 
|  | 346 | Once constructed, :class:`Decimal` objects are immutable. | 
|  | 347 |  | 
| Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 348 | .. versionchanged:: 2.6 | 
|  | 349 | leading and trailing whitespace characters are permitted when | 
|  | 350 | creating a Decimal instance from a string. | 
|  | 351 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 352 | Decimal floating point objects share many properties with the other built-in | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 353 | numeric types such as :class:`float` and :class:`int`.  All of the usual math | 
|  | 354 | operations and special methods apply.  Likewise, decimal objects can be copied, | 
|  | 355 | pickled, printed, used as dictionary keys, used as set elements, compared, | 
|  | 356 | sorted, and coerced to another type (such as :class:`float` or :class:`long`). | 
|  | 357 |  | 
|  | 358 | In addition to the standard numeric properties, decimal floating point objects | 
|  | 359 | also have a number of specialized methods: | 
|  | 360 |  | 
|  | 361 |  | 
|  | 362 | .. method:: Decimal.adjusted() | 
|  | 363 |  | 
|  | 364 | Return the adjusted exponent after shifting out the coefficient's rightmost | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 365 | digits until only the lead digit remains: ``Decimal('321e+5').adjusted()`` | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 366 | returns seven.  Used for determining the position of the most significant digit | 
|  | 367 | with respect to the decimal point. | 
|  | 368 |  | 
|  | 369 |  | 
|  | 370 | .. method:: Decimal.as_tuple() | 
|  | 371 |  | 
| Georg Brandl | e3c3db5 | 2008-01-11 09:55:53 +0000 | [diff] [blame] | 372 | Return a :term:`named tuple` representation of the number: | 
|  | 373 | ``DecimalTuple(sign, digits, exponent)``. | 
|  | 374 |  | 
|  | 375 | .. versionchanged:: 2.6 | 
|  | 376 | Use a named tuple. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 377 |  | 
|  | 378 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 379 | .. method:: Decimal.canonical() | 
|  | 380 |  | 
|  | 381 | Return the canonical encoding of the argument.  Currently, the | 
|  | 382 | encoding of a :class:`Decimal` instance is always canonical, so | 
|  | 383 | this operation returns its argument unchanged. | 
|  | 384 |  | 
|  | 385 | .. versionadded:: 2.6 | 
|  | 386 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 387 | .. method:: Decimal.compare(other[, context]) | 
|  | 388 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 389 | Compare the values of two Decimal instances.  This operation | 
|  | 390 | behaves in the same way as the usual comparison method | 
|  | 391 | :meth:`__cmp__`, except that :meth:`compare` returns a Decimal | 
|  | 392 | instance rather than an integer, and if either operand is a NaN | 
|  | 393 | then the result is a NaN:: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 394 |  | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 395 | a or b is a NaN ==> Decimal('NaN') | 
|  | 396 | a < b           ==> Decimal('-1') | 
|  | 397 | a == b          ==> Decimal('0') | 
|  | 398 | a > b           ==> Decimal('1') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 399 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 400 | .. method:: Decimal.compare_signal(other[, context]) | 
|  | 401 |  | 
|  | 402 | This operation is identical to the :meth:`compare` method, except | 
|  | 403 | that all NaNs signal.  That is, if neither operand is a signaling | 
|  | 404 | NaN then any quiet NaN operand is treated as though it were a | 
|  | 405 | signaling NaN. | 
|  | 406 |  | 
|  | 407 | .. versionadded:: 2.6 | 
|  | 408 |  | 
|  | 409 | .. method:: Decimal.compare_total(other) | 
|  | 410 |  | 
|  | 411 | Compare two operands using their abstract representation rather | 
|  | 412 | than their numerical value.  Similar to the :meth:`compare` method, | 
|  | 413 | but the result gives a total ordering on :class:`Decimal` | 
|  | 414 | instances.  Two :class:`Decimal` instances with the same numeric | 
|  | 415 | value but different representations compare unequal in this | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 416 | ordering: | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 417 |  | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 418 | >>> Decimal('12.0').compare_total(Decimal('12')) | 
|  | 419 | Decimal('-1') | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 420 |  | 
|  | 421 | Quiet and signaling NaNs are also included in the total ordering. | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 422 | The result of this function is ``Decimal('0')`` if both operands | 
|  | 423 | have the same representation, ``Decimal('-1')`` if the first | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 424 | operand is lower in the total order than the second, and | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 425 | ``Decimal('1')`` if the first operand is higher in the total order | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 426 | than the second operand.  See the specification for details of the | 
|  | 427 | total order. | 
|  | 428 |  | 
|  | 429 | .. versionadded:: 2.6 | 
|  | 430 |  | 
|  | 431 | .. method:: Decimal.compare_total_mag(other) | 
|  | 432 |  | 
|  | 433 | Compare two operands using their abstract representation rather | 
|  | 434 | than their value as in :meth:`compare_total`, but ignoring the sign | 
|  | 435 | of each operand.  ``x.compare_total_mag(y)`` is equivalent to | 
|  | 436 | ``x.copy_abs().compare_total(y.copy_abs())``. | 
|  | 437 |  | 
|  | 438 | .. versionadded:: 2.6 | 
|  | 439 |  | 
|  | 440 | .. method:: Decimal.copy_abs() | 
|  | 441 |  | 
|  | 442 | Return the absolute value of the argument.  This operation is | 
|  | 443 | unaffected by the context and is quiet: no flags are changed and no | 
|  | 444 | rounding is performed. | 
|  | 445 |  | 
|  | 446 | .. versionadded:: 2.6 | 
|  | 447 |  | 
|  | 448 | .. method:: Decimal.copy_negate() | 
|  | 449 |  | 
|  | 450 | Return the negation of the argument.  This operation is unaffected | 
|  | 451 | by the context and is quiet: no flags are changed and no rounding | 
|  | 452 | is performed. | 
|  | 453 |  | 
|  | 454 | .. versionadded:: 2.6 | 
|  | 455 |  | 
|  | 456 | .. method:: Decimal.copy_sign(other) | 
|  | 457 |  | 
|  | 458 | Return a copy of the first operand with the sign set to be the | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 459 | same as the sign of the second operand.  For example: | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 460 |  | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 461 | >>> Decimal('2.3').copy_sign(Decimal('-1.5')) | 
|  | 462 | Decimal('-2.3') | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 463 |  | 
|  | 464 | This operation is unaffected by the context and is quiet: no flags | 
|  | 465 | are changed and no rounding is performed. | 
|  | 466 |  | 
|  | 467 | .. versionadded:: 2.6 | 
|  | 468 |  | 
|  | 469 | .. method:: Decimal.exp([context]) | 
|  | 470 |  | 
|  | 471 | Return the value of the (natural) exponential function ``e**x`` at the | 
|  | 472 | given number.  The result is correctly rounded using the | 
|  | 473 | :const:`ROUND_HALF_EVEN` rounding mode. | 
|  | 474 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 475 | >>> Decimal(1).exp() | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 476 | Decimal('2.718281828459045235360287471') | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 477 | >>> Decimal(321).exp() | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 478 | Decimal('2.561702493119680037517373933E+139') | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 479 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 480 | .. versionadded:: 2.6 | 
|  | 481 |  | 
|  | 482 | .. method:: Decimal.fma(other, third[, context]) | 
|  | 483 |  | 
|  | 484 | Fused multiply-add.  Return self*other+third with no rounding of | 
|  | 485 | the intermediate product self*other. | 
|  | 486 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 487 | >>> Decimal(2).fma(3, 5) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 488 | Decimal('11') | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 489 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 490 | .. versionadded:: 2.6 | 
|  | 491 |  | 
|  | 492 | .. method:: Decimal.is_canonical() | 
|  | 493 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 494 | Return :const:`True` if the argument is canonical and | 
|  | 495 | :const:`False` otherwise.  Currently, a :class:`Decimal` instance | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 496 | is always canonical, so this operation always returns | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 497 | :const:`True`. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 498 |  | 
|  | 499 | .. versionadded:: 2.6 | 
|  | 500 |  | 
|  | 501 | .. method:: is_finite() | 
|  | 502 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 503 | Return :const:`True` if the argument is a finite number, and | 
|  | 504 | :const:`False` if the argument is an infinity or a NaN. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 505 |  | 
|  | 506 | .. versionadded:: 2.6 | 
|  | 507 |  | 
|  | 508 | .. method:: is_infinite() | 
|  | 509 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 510 | Return :const:`True` if the argument is either positive or | 
|  | 511 | negative infinity and :const:`False` otherwise. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 512 |  | 
|  | 513 | .. versionadded:: 2.6 | 
|  | 514 |  | 
|  | 515 | .. method:: is_nan() | 
|  | 516 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 517 | Return :const:`True` if the argument is a (quiet or signaling) | 
|  | 518 | NaN and :const:`False` otherwise. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 519 |  | 
|  | 520 | .. versionadded:: 2.6 | 
|  | 521 |  | 
|  | 522 | .. method:: is_normal() | 
|  | 523 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 524 | Return :const:`True` if the argument is a *normal* finite number. | 
|  | 525 | Return :const:`False` if the argument is zero, subnormal, infinite | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 526 | or a NaN. | 
|  | 527 |  | 
|  | 528 | .. versionadded:: 2.6 | 
|  | 529 |  | 
|  | 530 | .. method:: is_qnan() | 
|  | 531 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 532 | Return :const:`True` if the argument is a quiet NaN, and | 
|  | 533 | :const:`False` otherwise. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 534 |  | 
|  | 535 | .. versionadded:: 2.6 | 
|  | 536 |  | 
|  | 537 | .. method:: is_signed() | 
|  | 538 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 539 | Return :const:`True` if the argument has a negative sign and | 
|  | 540 | :const:`False` otherwise.  Note that zeros and NaNs can both carry | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 541 | signs. | 
|  | 542 |  | 
|  | 543 | .. versionadded:: 2.6 | 
|  | 544 |  | 
|  | 545 | .. method:: is_snan() | 
|  | 546 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 547 | Return :const:`True` if the argument is a signaling NaN and | 
|  | 548 | :const:`False` otherwise. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 549 |  | 
|  | 550 | .. versionadded:: 2.6 | 
|  | 551 |  | 
|  | 552 | .. method:: is_subnormal() | 
|  | 553 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 554 | Return :const:`True` if the argument is subnormal, and | 
|  | 555 | :const:`False` otherwise. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 556 |  | 
|  | 557 | .. versionadded:: 2.6 | 
|  | 558 |  | 
|  | 559 | .. method:: is_zero() | 
|  | 560 |  | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 561 | Return :const:`True` if the argument is a (positive or negative) | 
|  | 562 | zero and :const:`False` otherwise. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 563 |  | 
|  | 564 | .. versionadded:: 2.6 | 
|  | 565 |  | 
|  | 566 | .. method:: Decimal.ln([context]) | 
|  | 567 |  | 
|  | 568 | Return the natural (base e) logarithm of the operand.  The result | 
|  | 569 | is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding | 
|  | 570 | mode. | 
|  | 571 |  | 
|  | 572 | .. versionadded:: 2.6 | 
|  | 573 |  | 
|  | 574 | .. method:: Decimal.log10([context]) | 
|  | 575 |  | 
|  | 576 | Return the base ten logarithm of the operand.  The result is | 
|  | 577 | correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. | 
|  | 578 |  | 
|  | 579 | .. versionadded:: 2.6 | 
|  | 580 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 581 | .. method:: Decimal.logb([context]) | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 582 |  | 
|  | 583 | For a nonzero number, return the adjusted exponent of its operand | 
|  | 584 | as a :class:`Decimal` instance.  If the operand is a zero then | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 585 | ``Decimal('-Infinity')`` is returned and the | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 586 | :const:`DivisionByZero` flag is raised.  If the operand is an | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 587 | infinity then ``Decimal('Infinity')`` is returned. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 588 |  | 
|  | 589 | .. versionadded:: 2.6 | 
|  | 590 |  | 
|  | 591 | .. method:: Decimal.logical_and(other[, context]) | 
|  | 592 |  | 
|  | 593 | :meth:`logical_and` is a logical operation which takes two | 
|  | 594 | *logical operands* (see :ref:`logical_operands_label`).  The result | 
|  | 595 | is the digit-wise ``and`` of the two operands. | 
|  | 596 |  | 
|  | 597 | .. versionadded:: 2.6 | 
|  | 598 |  | 
|  | 599 | .. method:: Decimal.logical_invert(other[, context]) | 
|  | 600 |  | 
|  | 601 | :meth:`logical_invert` is a logical operation.  The argument must | 
|  | 602 | be a *logical operand* (see :ref:`logical_operands_label`).  The | 
|  | 603 | result is the digit-wise inversion of the operand. | 
|  | 604 |  | 
|  | 605 | .. versionadded:: 2.6 | 
|  | 606 |  | 
|  | 607 | .. method:: Decimal.logical_or(other[, context]) | 
|  | 608 |  | 
|  | 609 | :meth:`logical_or` is a logical operation which takes two *logical | 
|  | 610 | operands* (see :ref:`logical_operands_label`).  The result is the | 
|  | 611 | digit-wise ``or`` of the two operands. | 
|  | 612 |  | 
|  | 613 | .. versionadded:: 2.6 | 
|  | 614 |  | 
|  | 615 | .. method:: Decimal.logical_xor(other[, context]) | 
|  | 616 |  | 
|  | 617 | :meth:`logical_xor` is a logical operation which takes two | 
|  | 618 | *logical operands* (see :ref:`logical_operands_label`).  The result | 
|  | 619 | is the digit-wise exclusive or of the two operands. | 
|  | 620 |  | 
|  | 621 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 622 |  | 
|  | 623 | .. method:: Decimal.max(other[, context]) | 
|  | 624 |  | 
|  | 625 | Like ``max(self, other)`` except that the context rounding rule is applied | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 626 | before returning and that :const:`NaN` values are either signaled or ignored | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 627 | (depending on the context and whether they are signaling or quiet). | 
|  | 628 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 629 | .. method:: Decimal.max_mag(other[, context]) | 
|  | 630 |  | 
|  | 631 | Similar to the :meth:`max` method, but the comparison is done using | 
|  | 632 | the absolute values of the operands. | 
|  | 633 |  | 
|  | 634 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 635 |  | 
|  | 636 | .. method:: Decimal.min(other[, context]) | 
|  | 637 |  | 
|  | 638 | Like ``min(self, other)`` except that the context rounding rule is applied | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 639 | before returning and that :const:`NaN` values are either signaled or ignored | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 640 | (depending on the context and whether they are signaling or quiet). | 
|  | 641 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 642 | .. method:: Decimal.min_mag(other[, context]) | 
|  | 643 |  | 
|  | 644 | Similar to the :meth:`min` method, but the comparison is done using | 
|  | 645 | the absolute values of the operands. | 
|  | 646 |  | 
|  | 647 | .. versionadded:: 2.6 | 
|  | 648 |  | 
|  | 649 | .. method:: Decimal.next_minus([context]) | 
|  | 650 |  | 
|  | 651 | Return the largest number representable in the given context (or | 
|  | 652 | in the current thread's context if no context is given) that is smaller | 
|  | 653 | than the given operand. | 
|  | 654 |  | 
|  | 655 | .. versionadded:: 2.6 | 
|  | 656 |  | 
|  | 657 | .. method:: Decimal.next_plus([context]) | 
|  | 658 |  | 
|  | 659 | Return the smallest number representable in the given context (or | 
|  | 660 | in the current thread's context if no context is given) that is | 
|  | 661 | larger than the given operand. | 
|  | 662 |  | 
|  | 663 | .. versionadded:: 2.6 | 
|  | 664 |  | 
|  | 665 | .. method:: Decimal.next_toward(other[, context]) | 
|  | 666 |  | 
|  | 667 | If the two operands are unequal, return the number closest to the | 
|  | 668 | first operand in the direction of the second operand.  If both | 
|  | 669 | operands are numerically equal, return a copy of the first operand | 
|  | 670 | with the sign set to be the same as the sign of the second operand. | 
|  | 671 |  | 
|  | 672 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 673 |  | 
|  | 674 | .. method:: Decimal.normalize([context]) | 
|  | 675 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 676 | Normalize the number by stripping the rightmost trailing zeros and converting | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 677 | any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 678 | producing canonical values for members of an equivalence class. For example, | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 679 | ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the | 
|  | 680 | equivalent value ``Decimal('32.1')``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 681 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 682 | .. method:: Decimal.number_class([context]) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 683 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 684 | Return a string describing the *class* of the operand.  The | 
|  | 685 | returned value is one of the following ten strings. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 686 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 687 | * ``"-Infinity"``, indicating that the operand is negative infinity. | 
|  | 688 | * ``"-Normal"``, indicating that the operand is a negative normal number. | 
|  | 689 | * ``"-Subnormal"``, indicating that the operand is negative and subnormal. | 
|  | 690 | * ``"-Zero"``, indicating that the operand is a negative zero. | 
|  | 691 | * ``"+Zero"``, indicating that the operand is a positive zero. | 
|  | 692 | * ``"+Subnormal"``, indicating that the operand is positive and subnormal. | 
|  | 693 | * ``"+Normal"``, indicating that the operand is a positive normal number. | 
|  | 694 | * ``"+Infinity"``, indicating that the operand is positive infinity. | 
|  | 695 | * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). | 
|  | 696 | * ``"sNaN"``, indicating that the operand is a signaling NaN. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 697 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 698 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 699 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 700 | .. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) | 
|  | 701 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 702 | Return a value equal to the first operand after rounding and | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 703 | having the exponent of the second operand. | 
|  | 704 |  | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 705 | >>> Decimal('1.41421356').quantize(Decimal('1.000')) | 
|  | 706 | Decimal('1.414') | 
| Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 707 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 708 | Unlike other operations, if the length of the coefficient after the | 
|  | 709 | quantize operation would be greater than precision, then an | 
|  | 710 | :const:`InvalidOperation` is signaled. This guarantees that, unless | 
|  | 711 | there is an error condition, the quantized exponent is always equal | 
|  | 712 | to that of the right-hand operand. | 
|  | 713 |  | 
|  | 714 | Also unlike other operations, quantize never signals Underflow, | 
|  | 715 | even if the result is subnormal and inexact. | 
|  | 716 |  | 
|  | 717 | If the exponent of the second operand is larger than that of the | 
|  | 718 | first then rounding may be necessary.  In this case, the rounding | 
|  | 719 | mode is determined by the ``rounding`` argument if given, else by | 
|  | 720 | the given ``context`` argument; if neither argument is given the | 
|  | 721 | rounding mode of the current thread's context is used. | 
|  | 722 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 723 | If *watchexp* is set (default), then an error is returned whenever the | 
|  | 724 | resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 725 |  | 
|  | 726 | .. method:: Decimal.radix() | 
|  | 727 |  | 
|  | 728 | Return ``Decimal(10)``, the radix (base) in which the | 
|  | 729 | :class:`Decimal` class does all its arithmetic.  Included for | 
|  | 730 | compatibility with the specification. | 
|  | 731 |  | 
|  | 732 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 733 |  | 
|  | 734 | .. method:: Decimal.remainder_near(other[, context]) | 
|  | 735 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 736 | Compute the modulo as either a positive or negative value depending on which is | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 737 | closest to zero.  For instance, ``Decimal(10).remainder_near(6)`` returns | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 738 | ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 739 |  | 
|  | 740 | If both are equally close, the one chosen will have the same sign as *self*. | 
|  | 741 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 742 | .. method:: Decimal.rotate(other[, context]) | 
|  | 743 |  | 
|  | 744 | Return the result of rotating the digits of the first operand by | 
|  | 745 | an amount specified by the second operand.  The second operand | 
|  | 746 | must be an integer in the range -precision through precision.  The | 
|  | 747 | absolute value of the second operand gives the number of places to | 
|  | 748 | rotate.  If the second operand is positive then rotation is to the | 
|  | 749 | left; otherwise rotation is to the right.  The coefficient of the | 
|  | 750 | first operand is padded on the left with zeros to length precision | 
|  | 751 | if necessary.  The sign and exponent of the first operand are | 
|  | 752 | unchanged. | 
|  | 753 |  | 
|  | 754 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 755 |  | 
|  | 756 | .. method:: Decimal.same_quantum(other[, context]) | 
|  | 757 |  | 
|  | 758 | Test whether self and other have the same exponent or whether both are | 
|  | 759 | :const:`NaN`. | 
|  | 760 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 761 | .. method:: Decimal.scaleb(other[, context]) | 
|  | 762 |  | 
|  | 763 | Return the first operand with exponent adjusted by the second. | 
|  | 764 | Equivalently, return the first operand multiplied by ``10**other``. | 
|  | 765 | The second operand must be an integer. | 
|  | 766 |  | 
|  | 767 | .. versionadded:: 2.6 | 
|  | 768 |  | 
|  | 769 | .. method:: Decimal.shift(other[, context]) | 
|  | 770 |  | 
|  | 771 | Return the result of shifting the digits of the first operand by | 
|  | 772 | an amount specified by the second operand.  The second operand must | 
|  | 773 | be an integer in the range -precision through precision.  The | 
|  | 774 | absolute value of the second operand gives the number of places to | 
|  | 775 | shift.  If the second operand is positive then the shift is to the | 
|  | 776 | left; otherwise the shift is to the right.  Digits shifted into the | 
|  | 777 | coefficient are zeros.  The sign and exponent of the first operand | 
|  | 778 | are unchanged. | 
|  | 779 |  | 
|  | 780 | .. versionadded:: 2.6 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 781 |  | 
|  | 782 | .. method:: Decimal.sqrt([context]) | 
|  | 783 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 784 | Return the square root of the argument to full precision. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 785 |  | 
|  | 786 |  | 
|  | 787 | .. method:: Decimal.to_eng_string([context]) | 
|  | 788 |  | 
|  | 789 | Convert to an engineering-type string. | 
|  | 790 |  | 
|  | 791 | Engineering notation has an exponent which is a multiple of 3, so there are up | 
|  | 792 | to 3 digits left of the decimal place.  For example, converts | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 793 | ``Decimal('123E+1')`` to ``Decimal('1.23E+3')`` | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 794 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 795 | .. method:: Decimal.to_integral([rounding[, context]]) | 
|  | 796 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 797 | Identical to the :meth:`to_integral_value` method.  The ``to_integral`` | 
|  | 798 | name has been kept for compatibility with older versions. | 
|  | 799 |  | 
|  | 800 | .. method:: Decimal.to_integral_exact([rounding[, context]]) | 
|  | 801 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 802 | Round to the nearest integer, signaling | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 803 | :const:`Inexact` or :const:`Rounded` as appropriate if rounding | 
|  | 804 | occurs.  The rounding mode is determined by the ``rounding`` | 
|  | 805 | parameter if given, else by the given ``context``.  If neither | 
|  | 806 | parameter is given then the rounding mode of the current context is | 
|  | 807 | used. | 
|  | 808 |  | 
|  | 809 | .. versionadded:: 2.6 | 
|  | 810 |  | 
|  | 811 | .. method:: Decimal.to_integral_value([rounding[, context]]) | 
|  | 812 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 813 | Round to the nearest integer without signaling :const:`Inexact` or | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 814 | :const:`Rounded`.  If given, applies *rounding*; otherwise, uses the rounding | 
|  | 815 | method in either the supplied *context* or the current context. | 
|  | 816 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 817 | .. versionchanged:: 2.6 | 
|  | 818 | renamed from ``to_integral`` to ``to_integral_value``.  The old name | 
|  | 819 | remains valid for compatibility. | 
|  | 820 |  | 
|  | 821 | .. method:: Decimal.trim() | 
|  | 822 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 823 | Return the decimal with *insignificant* trailing zeros removed. | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 824 | Here, a trailing zero is considered insignificant either if it | 
|  | 825 | follows the decimal point, or if the exponent of the argument (that | 
|  | 826 | is, the last element of the :meth:`as_tuple` representation) is | 
|  | 827 | positive. | 
|  | 828 |  | 
|  | 829 | .. versionadded:: 2.6 | 
|  | 830 |  | 
|  | 831 | .. _logical_operands_label: | 
|  | 832 |  | 
|  | 833 | Logical operands | 
|  | 834 | ^^^^^^^^^^^^^^^^ | 
|  | 835 |  | 
|  | 836 | The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`, | 
|  | 837 | and :meth:`logical_xor` methods expect their arguments to be *logical | 
|  | 838 | operands*.  A *logical operand* is a :class:`Decimal` instance whose | 
|  | 839 | exponent and sign are both zero, and whose digits are all either | 
|  | 840 | :const:`0` or :const:`1`. | 
|  | 841 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 842 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 843 |  | 
|  | 844 |  | 
|  | 845 | .. _decimal-context: | 
|  | 846 |  | 
|  | 847 | Context objects | 
|  | 848 | --------------- | 
|  | 849 |  | 
|  | 850 | Contexts are environments for arithmetic operations.  They govern precision, set | 
|  | 851 | rules for rounding, determine which signals are treated as exceptions, and limit | 
|  | 852 | the range for exponents. | 
|  | 853 |  | 
|  | 854 | Each thread has its own current context which is accessed or changed using the | 
|  | 855 | :func:`getcontext` and :func:`setcontext` functions: | 
|  | 856 |  | 
|  | 857 |  | 
|  | 858 | .. function:: getcontext() | 
|  | 859 |  | 
|  | 860 | Return the current context for the active thread. | 
|  | 861 |  | 
|  | 862 |  | 
|  | 863 | .. function:: setcontext(c) | 
|  | 864 |  | 
|  | 865 | Set the current context for the active thread to *c*. | 
|  | 866 |  | 
|  | 867 | Beginning with Python 2.5, you can also use the :keyword:`with` statement and | 
|  | 868 | the :func:`localcontext` function to temporarily change the active context. | 
|  | 869 |  | 
|  | 870 |  | 
|  | 871 | .. function:: localcontext([c]) | 
|  | 872 |  | 
|  | 873 | Return a context manager that will set the current context for the active thread | 
|  | 874 | to a copy of *c* on entry to the with-statement and restore the previous context | 
|  | 875 | when exiting the with-statement. If no context is specified, a copy of the | 
|  | 876 | current context is used. | 
|  | 877 |  | 
|  | 878 | .. versionadded:: 2.5 | 
|  | 879 |  | 
|  | 880 | For example, the following code sets the current decimal precision to 42 places, | 
|  | 881 | performs a calculation, and then automatically restores the previous context:: | 
|  | 882 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 883 | from decimal import localcontext | 
|  | 884 |  | 
|  | 885 | with localcontext() as ctx: | 
|  | 886 | ctx.prec = 42   # Perform a high precision calculation | 
|  | 887 | s = calculate_something() | 
|  | 888 | s = +s  # Round the final result back to the default precision | 
|  | 889 |  | 
|  | 890 | New contexts can also be created using the :class:`Context` constructor | 
|  | 891 | described below. In addition, the module provides three pre-made contexts: | 
|  | 892 |  | 
|  | 893 |  | 
|  | 894 | .. class:: BasicContext | 
|  | 895 |  | 
|  | 896 | This is a standard context defined by the General Decimal Arithmetic | 
|  | 897 | Specification.  Precision is set to nine.  Rounding is set to | 
|  | 898 | :const:`ROUND_HALF_UP`.  All flags are cleared.  All traps are enabled (treated | 
|  | 899 | as exceptions) except :const:`Inexact`, :const:`Rounded`, and | 
|  | 900 | :const:`Subnormal`. | 
|  | 901 |  | 
|  | 902 | Because many of the traps are enabled, this context is useful for debugging. | 
|  | 903 |  | 
|  | 904 |  | 
|  | 905 | .. class:: ExtendedContext | 
|  | 906 |  | 
|  | 907 | This is a standard context defined by the General Decimal Arithmetic | 
|  | 908 | Specification.  Precision is set to nine.  Rounding is set to | 
|  | 909 | :const:`ROUND_HALF_EVEN`.  All flags are cleared.  No traps are enabled (so that | 
|  | 910 | exceptions are not raised during computations). | 
|  | 911 |  | 
| Mark Dickinson | 3a94ee0 | 2008-02-10 15:19:58 +0000 | [diff] [blame] | 912 | Because the traps are disabled, this context is useful for applications that | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 913 | prefer to have result value of :const:`NaN` or :const:`Infinity` instead of | 
|  | 914 | raising exceptions.  This allows an application to complete a run in the | 
|  | 915 | presence of conditions that would otherwise halt the program. | 
|  | 916 |  | 
|  | 917 |  | 
|  | 918 | .. class:: DefaultContext | 
|  | 919 |  | 
|  | 920 | This context is used by the :class:`Context` constructor as a prototype for new | 
|  | 921 | contexts.  Changing a field (such a precision) has the effect of changing the | 
|  | 922 | default for new contexts creating by the :class:`Context` constructor. | 
|  | 923 |  | 
|  | 924 | This context is most useful in multi-threaded environments.  Changing one of the | 
|  | 925 | fields before threads are started has the effect of setting system-wide | 
|  | 926 | defaults.  Changing the fields after threads have started is not recommended as | 
|  | 927 | it would require thread synchronization to prevent race conditions. | 
|  | 928 |  | 
|  | 929 | In single threaded environments, it is preferable to not use this context at | 
|  | 930 | all.  Instead, simply create contexts explicitly as described below. | 
|  | 931 |  | 
|  | 932 | The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps | 
|  | 933 | for Overflow, InvalidOperation, and DivisionByZero. | 
|  | 934 |  | 
|  | 935 | In addition to the three supplied contexts, new contexts can be created with the | 
|  | 936 | :class:`Context` constructor. | 
|  | 937 |  | 
|  | 938 |  | 
|  | 939 | .. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1) | 
|  | 940 |  | 
|  | 941 | Creates a new context.  If a field is not specified or is :const:`None`, the | 
|  | 942 | default values are copied from the :const:`DefaultContext`.  If the *flags* | 
|  | 943 | field is not specified or is :const:`None`, all flags are cleared. | 
|  | 944 |  | 
|  | 945 | The *prec* field is a positive integer that sets the precision for arithmetic | 
|  | 946 | operations in the context. | 
|  | 947 |  | 
|  | 948 | The *rounding* option is one of: | 
|  | 949 |  | 
|  | 950 | * :const:`ROUND_CEILING` (towards :const:`Infinity`), | 
|  | 951 | * :const:`ROUND_DOWN` (towards zero), | 
|  | 952 | * :const:`ROUND_FLOOR` (towards :const:`-Infinity`), | 
|  | 953 | * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero), | 
|  | 954 | * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer), | 
|  | 955 | * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or | 
|  | 956 | * :const:`ROUND_UP` (away from zero). | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 957 | * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero | 
|  | 958 | would have been 0 or 5; otherwise towards zero) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 959 |  | 
|  | 960 | The *traps* and *flags* fields list any signals to be set. Generally, new | 
|  | 961 | contexts should only set traps and leave the flags clear. | 
|  | 962 |  | 
|  | 963 | The *Emin* and *Emax* fields are integers specifying the outer limits allowable | 
|  | 964 | for exponents. | 
|  | 965 |  | 
|  | 966 | The *capitals* field is either :const:`0` or :const:`1` (the default). If set to | 
|  | 967 | :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a | 
|  | 968 | lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. | 
|  | 969 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 970 | .. versionchanged:: 2.6 | 
|  | 971 | The :const:`ROUND_05UP` rounding mode was added. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 972 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 973 | The :class:`Context` class defines several general purpose methods as | 
|  | 974 | well as a large number of methods for doing arithmetic directly in a | 
|  | 975 | given context.  In addition, for each of the :class:`Decimal` methods | 
|  | 976 | described above (with the exception of the :meth:`adjusted` and | 
|  | 977 | :meth:`as_tuple` methods) there is a corresponding :class:`Context` | 
|  | 978 | method.  For example, ``C.exp(x)`` is equivalent to | 
|  | 979 | ``x.exp(context=C)``. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 980 |  | 
|  | 981 | .. method:: Context.clear_flags() | 
|  | 982 |  | 
|  | 983 | Resets all of the flags to :const:`0`. | 
|  | 984 |  | 
|  | 985 |  | 
|  | 986 | .. method:: Context.copy() | 
|  | 987 |  | 
|  | 988 | Return a duplicate of the context. | 
|  | 989 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 990 | .. method:: Context.copy_decimal(num) | 
|  | 991 |  | 
|  | 992 | Return a copy of the Decimal instance num. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 993 |  | 
|  | 994 | .. method:: Context.create_decimal(num) | 
|  | 995 |  | 
|  | 996 | Creates a new Decimal instance from *num* but using *self* as context. Unlike | 
|  | 997 | the :class:`Decimal` constructor, the context precision, rounding method, flags, | 
|  | 998 | and traps are applied to the conversion. | 
|  | 999 |  | 
|  | 1000 | This is useful because constants are often given to a greater precision than is | 
|  | 1001 | needed by the application.  Another benefit is that rounding immediately | 
|  | 1002 | eliminates unintended effects from digits beyond the current precision. In the | 
|  | 1003 | following example, using unrounded inputs means that adding zero to a sum can | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1004 | change the result: | 
|  | 1005 |  | 
|  | 1006 | .. doctest:: newcontext | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1007 |  | 
|  | 1008 | >>> getcontext().prec = 3 | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1009 | >>> Decimal('3.4445') + Decimal('1.0023') | 
|  | 1010 | Decimal('4.45') | 
|  | 1011 | >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') | 
|  | 1012 | Decimal('4.44') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1013 |  | 
| Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 1014 | This method implements the to-number operation of the IBM | 
|  | 1015 | specification.  If the argument is a string, no leading or trailing | 
|  | 1016 | whitespace is permitted. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1017 |  | 
|  | 1018 | .. method:: Context.Etiny() | 
|  | 1019 |  | 
|  | 1020 | Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value | 
|  | 1021 | for subnormal results.  When underflow occurs, the exponent is set to | 
|  | 1022 | :const:`Etiny`. | 
|  | 1023 |  | 
|  | 1024 |  | 
|  | 1025 | .. method:: Context.Etop() | 
|  | 1026 |  | 
|  | 1027 | Returns a value equal to ``Emax - prec + 1``. | 
|  | 1028 |  | 
|  | 1029 | The usual approach to working with decimals is to create :class:`Decimal` | 
|  | 1030 | instances and then apply arithmetic operations which take place within the | 
| Georg Brandl | 5d242ee | 2007-09-20 08:44:59 +0000 | [diff] [blame] | 1031 | current context for the active thread.  An alternative approach is to use context | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1032 | methods for calculating within a specific context.  The methods are similar to | 
|  | 1033 | those for the :class:`Decimal` class and are only briefly recounted here. | 
|  | 1034 |  | 
|  | 1035 |  | 
|  | 1036 | .. method:: Context.abs(x) | 
|  | 1037 |  | 
|  | 1038 | Returns the absolute value of *x*. | 
|  | 1039 |  | 
|  | 1040 |  | 
|  | 1041 | .. method:: Context.add(x, y) | 
|  | 1042 |  | 
|  | 1043 | Return the sum of *x* and *y*. | 
|  | 1044 |  | 
|  | 1045 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1046 | .. method:: Context.divide(x, y) | 
|  | 1047 |  | 
|  | 1048 | Return *x* divided by *y*. | 
|  | 1049 |  | 
|  | 1050 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1051 | .. method:: Context.divide_int(x, y) | 
|  | 1052 |  | 
|  | 1053 | Return *x* divided by *y*, truncated to an integer. | 
|  | 1054 |  | 
|  | 1055 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1056 | .. method:: Context.divmod(x, y) | 
|  | 1057 |  | 
|  | 1058 | Divides two numbers and returns the integer part of the result. | 
|  | 1059 |  | 
|  | 1060 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1061 | .. method:: Context.minus(x) | 
|  | 1062 |  | 
|  | 1063 | Minus corresponds to the unary prefix minus operator in Python. | 
|  | 1064 |  | 
|  | 1065 |  | 
|  | 1066 | .. method:: Context.multiply(x, y) | 
|  | 1067 |  | 
|  | 1068 | Return the product of *x* and *y*. | 
|  | 1069 |  | 
|  | 1070 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1071 | .. method:: Context.plus(x) | 
|  | 1072 |  | 
|  | 1073 | Plus corresponds to the unary prefix plus operator in Python.  This operation | 
|  | 1074 | applies the context precision and rounding, so it is *not* an identity | 
|  | 1075 | operation. | 
|  | 1076 |  | 
|  | 1077 |  | 
|  | 1078 | .. method:: Context.power(x, y[, modulo]) | 
|  | 1079 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1080 | Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if | 
|  | 1081 | given. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1082 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1083 | With two arguments, compute ``x**y``.  If ``x`` is negative then | 
|  | 1084 | ``y`` must be integral.  The result will be inexact unless ``y`` is | 
|  | 1085 | integral and the result is finite and can be expressed exactly in | 
|  | 1086 | 'precision' digits.  The result should always be correctly rounded, | 
|  | 1087 | using the rounding mode of the current thread's context. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1088 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1089 | With three arguments, compute ``(x**y) % modulo``.  For the three | 
|  | 1090 | argument form, the following restrictions on the arguments hold: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1091 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1092 | - all three arguments must be integral | 
|  | 1093 | - ``y`` must be nonnegative | 
|  | 1094 | - at least one of ``x`` or ``y`` must be nonzero | 
|  | 1095 | - ``modulo`` must be nonzero and have at most 'precision' digits | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1096 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1097 | The result of ``Context.power(x, y, modulo)`` is identical to | 
|  | 1098 | the result that would be obtained by computing ``(x**y) % | 
|  | 1099 | modulo`` with unbounded precision, but is computed more | 
|  | 1100 | efficiently.  It is always exact. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1101 |  | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1102 | .. versionchanged:: 2.6 | 
|  | 1103 | ``y`` may now be nonintegral in ``x**y``. | 
|  | 1104 | Stricter requirements for the three-argument version. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1105 |  | 
|  | 1106 |  | 
|  | 1107 | .. method:: Context.remainder(x, y) | 
|  | 1108 |  | 
|  | 1109 | Returns the remainder from integer division. | 
|  | 1110 |  | 
|  | 1111 | The sign of the result, if non-zero, is the same as that of the original | 
|  | 1112 | dividend. | 
|  | 1113 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1114 | .. method:: Context.subtract(x, y) | 
|  | 1115 |  | 
|  | 1116 | Return the difference between *x* and *y*. | 
|  | 1117 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1118 | .. method:: Context.to_sci_string(x) | 
|  | 1119 |  | 
|  | 1120 | Converts a number to a string using scientific notation. | 
|  | 1121 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1122 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1123 |  | 
|  | 1124 |  | 
|  | 1125 | .. _decimal-signals: | 
|  | 1126 |  | 
|  | 1127 | Signals | 
|  | 1128 | ------- | 
|  | 1129 |  | 
|  | 1130 | Signals represent conditions that arise during computation. Each corresponds to | 
|  | 1131 | one context flag and one context trap enabler. | 
|  | 1132 |  | 
|  | 1133 | The context flag is incremented whenever the condition is encountered. After the | 
|  | 1134 | computation, flags may be checked for informational purposes (for instance, to | 
|  | 1135 | determine whether a computation was exact). After checking the flags, be sure to | 
|  | 1136 | clear all flags before starting the next computation. | 
|  | 1137 |  | 
|  | 1138 | If the context's trap enabler is set for the signal, then the condition causes a | 
|  | 1139 | Python exception to be raised.  For example, if the :class:`DivisionByZero` trap | 
|  | 1140 | is set, then a :exc:`DivisionByZero` exception is raised upon encountering the | 
|  | 1141 | condition. | 
|  | 1142 |  | 
|  | 1143 |  | 
|  | 1144 | .. class:: Clamped | 
|  | 1145 |  | 
|  | 1146 | Altered an exponent to fit representation constraints. | 
|  | 1147 |  | 
|  | 1148 | Typically, clamping occurs when an exponent falls outside the context's | 
|  | 1149 | :attr:`Emin` and :attr:`Emax` limits.  If possible, the exponent is reduced to | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1150 | fit by adding zeros to the coefficient. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1151 |  | 
|  | 1152 |  | 
|  | 1153 | .. class:: DecimalException | 
|  | 1154 |  | 
|  | 1155 | Base class for other signals and a subclass of :exc:`ArithmeticError`. | 
|  | 1156 |  | 
|  | 1157 |  | 
|  | 1158 | .. class:: DivisionByZero | 
|  | 1159 |  | 
|  | 1160 | Signals the division of a non-infinite number by zero. | 
|  | 1161 |  | 
|  | 1162 | Can occur with division, modulo division, or when raising a number to a negative | 
|  | 1163 | power.  If this signal is not trapped, returns :const:`Infinity` or | 
|  | 1164 | :const:`-Infinity` with the sign determined by the inputs to the calculation. | 
|  | 1165 |  | 
|  | 1166 |  | 
|  | 1167 | .. class:: Inexact | 
|  | 1168 |  | 
|  | 1169 | Indicates that rounding occurred and the result is not exact. | 
|  | 1170 |  | 
|  | 1171 | Signals when non-zero digits were discarded during rounding. The rounded result | 
|  | 1172 | is returned.  The signal flag or trap is used to detect when results are | 
|  | 1173 | inexact. | 
|  | 1174 |  | 
|  | 1175 |  | 
|  | 1176 | .. class:: InvalidOperation | 
|  | 1177 |  | 
|  | 1178 | An invalid operation was performed. | 
|  | 1179 |  | 
|  | 1180 | Indicates that an operation was requested that does not make sense. If not | 
|  | 1181 | trapped, returns :const:`NaN`.  Possible causes include:: | 
|  | 1182 |  | 
|  | 1183 | Infinity - Infinity | 
|  | 1184 | 0 * Infinity | 
|  | 1185 | Infinity / Infinity | 
|  | 1186 | x % 0 | 
|  | 1187 | Infinity % x | 
|  | 1188 | x._rescale( non-integer ) | 
|  | 1189 | sqrt(-x) and x > 0 | 
|  | 1190 | 0 ** 0 | 
|  | 1191 | x ** (non-integer) | 
|  | 1192 | x ** Infinity | 
|  | 1193 |  | 
|  | 1194 |  | 
|  | 1195 | .. class:: Overflow | 
|  | 1196 |  | 
|  | 1197 | Numerical overflow. | 
|  | 1198 |  | 
|  | 1199 | Indicates the exponent is larger than :attr:`Emax` after rounding has occurred. | 
|  | 1200 | If not trapped, the result depends on the rounding mode, either pulling inward | 
|  | 1201 | to the largest representable finite number or rounding outward to | 
|  | 1202 | :const:`Infinity`.  In either case, :class:`Inexact` and :class:`Rounded` are | 
|  | 1203 | also signaled. | 
|  | 1204 |  | 
|  | 1205 |  | 
|  | 1206 | .. class:: Rounded | 
|  | 1207 |  | 
|  | 1208 | Rounding occurred though possibly no information was lost. | 
|  | 1209 |  | 
|  | 1210 | Signaled whenever rounding discards digits; even if those digits are zero (such | 
|  | 1211 | as rounding :const:`5.00` to :const:`5.0`).   If not trapped, returns the result | 
|  | 1212 | unchanged.  This signal is used to detect loss of significant digits. | 
|  | 1213 |  | 
|  | 1214 |  | 
|  | 1215 | .. class:: Subnormal | 
|  | 1216 |  | 
|  | 1217 | Exponent was lower than :attr:`Emin` prior to rounding. | 
|  | 1218 |  | 
|  | 1219 | Occurs when an operation result is subnormal (the exponent is too small). If not | 
|  | 1220 | trapped, returns the result unchanged. | 
|  | 1221 |  | 
|  | 1222 |  | 
|  | 1223 | .. class:: Underflow | 
|  | 1224 |  | 
|  | 1225 | Numerical underflow with result rounded to zero. | 
|  | 1226 |  | 
|  | 1227 | Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact` | 
|  | 1228 | and :class:`Subnormal` are also signaled. | 
|  | 1229 |  | 
|  | 1230 | The following table summarizes the hierarchy of signals:: | 
|  | 1231 |  | 
|  | 1232 | exceptions.ArithmeticError(exceptions.StandardError) | 
|  | 1233 | DecimalException | 
|  | 1234 | Clamped | 
|  | 1235 | DivisionByZero(DecimalException, exceptions.ZeroDivisionError) | 
|  | 1236 | Inexact | 
|  | 1237 | Overflow(Inexact, Rounded) | 
|  | 1238 | Underflow(Inexact, Rounded, Subnormal) | 
|  | 1239 | InvalidOperation | 
|  | 1240 | Rounded | 
|  | 1241 | Subnormal | 
|  | 1242 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1243 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1244 |  | 
|  | 1245 |  | 
|  | 1246 | .. _decimal-notes: | 
|  | 1247 |  | 
|  | 1248 | Floating Point Notes | 
|  | 1249 | -------------------- | 
|  | 1250 |  | 
|  | 1251 |  | 
|  | 1252 | Mitigating round-off error with increased precision | 
|  | 1253 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 1254 |  | 
|  | 1255 | The use of decimal floating point eliminates decimal representation error | 
|  | 1256 | (making it possible to represent :const:`0.1` exactly); however, some operations | 
|  | 1257 | can still incur round-off error when non-zero digits exceed the fixed precision. | 
|  | 1258 |  | 
|  | 1259 | The effects of round-off error can be amplified by the addition or subtraction | 
|  | 1260 | of nearly offsetting quantities resulting in loss of significance.  Knuth | 
|  | 1261 | provides two instructive examples where rounded floating point arithmetic with | 
|  | 1262 | insufficient precision causes the breakdown of the associative and distributive | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1263 | properties of addition: | 
|  | 1264 |  | 
|  | 1265 | .. doctest:: newcontext | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1266 |  | 
|  | 1267 | # Examples from Seminumerical Algorithms, Section 4.2.2. | 
|  | 1268 | >>> from decimal import Decimal, getcontext | 
|  | 1269 | >>> getcontext().prec = 8 | 
|  | 1270 |  | 
|  | 1271 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') | 
|  | 1272 | >>> (u + v) + w | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1273 | Decimal('9.5111111') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1274 | >>> u + (v + w) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1275 | Decimal('10') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1276 |  | 
|  | 1277 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') | 
|  | 1278 | >>> (u*v) + (u*w) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1279 | Decimal('0.01') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1280 | >>> u * (v+w) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1281 | Decimal('0.0060000') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1282 |  | 
|  | 1283 | The :mod:`decimal` module makes it possible to restore the identities by | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1284 | expanding the precision sufficiently to avoid loss of significance: | 
|  | 1285 |  | 
|  | 1286 | .. doctest:: newcontext | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1287 |  | 
|  | 1288 | >>> getcontext().prec = 20 | 
|  | 1289 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') | 
|  | 1290 | >>> (u + v) + w | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1291 | Decimal('9.51111111') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1292 | >>> u + (v + w) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1293 | Decimal('9.51111111') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1294 | >>> | 
|  | 1295 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') | 
|  | 1296 | >>> (u*v) + (u*w) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1297 | Decimal('0.0060000') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1298 | >>> u * (v+w) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1299 | Decimal('0.0060000') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1300 |  | 
|  | 1301 |  | 
|  | 1302 | Special values | 
|  | 1303 | ^^^^^^^^^^^^^^ | 
|  | 1304 |  | 
|  | 1305 | The number system for the :mod:`decimal` module provides special values | 
|  | 1306 | including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`, | 
| Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1307 | and two zeros, :const:`+0` and :const:`-0`. | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1308 |  | 
|  | 1309 | Infinities can be constructed directly with:  ``Decimal('Infinity')``. Also, | 
|  | 1310 | they can arise from dividing by zero when the :exc:`DivisionByZero` signal is | 
|  | 1311 | not trapped.  Likewise, when the :exc:`Overflow` signal is not trapped, infinity | 
|  | 1312 | can result from rounding beyond the limits of the largest representable number. | 
|  | 1313 |  | 
|  | 1314 | The infinities are signed (affine) and can be used in arithmetic operations | 
|  | 1315 | where they get treated as very large, indeterminate numbers.  For instance, | 
|  | 1316 | adding a constant to infinity gives another infinite result. | 
|  | 1317 |  | 
|  | 1318 | Some operations are indeterminate and return :const:`NaN`, or if the | 
|  | 1319 | :exc:`InvalidOperation` signal is trapped, raise an exception.  For example, | 
|  | 1320 | ``0/0`` returns :const:`NaN` which means "not a number".  This variety of | 
|  | 1321 | :const:`NaN` is quiet and, once created, will flow through other computations | 
|  | 1322 | always resulting in another :const:`NaN`.  This behavior can be useful for a | 
|  | 1323 | series of computations that occasionally have missing inputs --- it allows the | 
|  | 1324 | calculation to proceed while flagging specific results as invalid. | 
|  | 1325 |  | 
|  | 1326 | A variant is :const:`sNaN` which signals rather than remaining quiet after every | 
|  | 1327 | operation.  This is a useful return value when an invalid result needs to | 
|  | 1328 | interrupt a calculation for special handling. | 
|  | 1329 |  | 
| Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 1330 | The behavior of Python's comparison operators can be a little surprising where a | 
|  | 1331 | :const:`NaN` is involved.  A test for equality where one of the operands is a | 
|  | 1332 | quiet or signaling :const:`NaN` always returns :const:`False` (even when doing | 
|  | 1333 | ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns | 
| Mark Dickinson | bafa942 | 2008-02-06 22:25:16 +0000 | [diff] [blame] | 1334 | :const:`True`.  An attempt to compare two Decimals using any of the ``<``, | 
| Mark Dickinson | 00c2e65 | 2008-02-07 01:42:06 +0000 | [diff] [blame] | 1335 | ``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal | 
|  | 1336 | if either operand is a :const:`NaN`, and return :const:`False` if this signal is | 
| Mark Dickinson | 3a94ee0 | 2008-02-10 15:19:58 +0000 | [diff] [blame] | 1337 | not trapped.  Note that the General Decimal Arithmetic specification does not | 
| Mark Dickinson | 00c2e65 | 2008-02-07 01:42:06 +0000 | [diff] [blame] | 1338 | specify the behavior of direct comparisons; these rules for comparisons | 
|  | 1339 | involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in | 
|  | 1340 | section 5.7).  To ensure strict standards-compliance, use the :meth:`compare` | 
| Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 1341 | and :meth:`compare-signal` methods instead. | 
|  | 1342 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1343 | The signed zeros can result from calculations that underflow. They keep the sign | 
|  | 1344 | that would have resulted if the calculation had been carried out to greater | 
|  | 1345 | precision.  Since their magnitude is zero, both positive and negative zeros are | 
|  | 1346 | treated as equal and their sign is informational. | 
|  | 1347 |  | 
|  | 1348 | In addition to the two signed zeros which are distinct yet equal, there are | 
|  | 1349 | various representations of zero with differing precisions yet equivalent in | 
|  | 1350 | value.  This takes a bit of getting used to.  For an eye accustomed to | 
|  | 1351 | normalized floating point representations, it is not immediately obvious that | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1352 | the following calculation returns a value equal to zero: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1353 |  | 
|  | 1354 | >>> 1 / Decimal('Infinity') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1355 | Decimal('0E-1000000026') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1356 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1357 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1358 |  | 
|  | 1359 |  | 
|  | 1360 | .. _decimal-threads: | 
|  | 1361 |  | 
|  | 1362 | Working with threads | 
|  | 1363 | -------------------- | 
|  | 1364 |  | 
|  | 1365 | The :func:`getcontext` function accesses a different :class:`Context` object for | 
|  | 1366 | each thread.  Having separate thread contexts means that threads may make | 
|  | 1367 | changes (such as ``getcontext.prec=10``) without interfering with other threads. | 
|  | 1368 |  | 
|  | 1369 | Likewise, the :func:`setcontext` function automatically assigns its target to | 
|  | 1370 | the current thread. | 
|  | 1371 |  | 
|  | 1372 | If :func:`setcontext` has not been called before :func:`getcontext`, then | 
|  | 1373 | :func:`getcontext` will automatically create a new context for use in the | 
|  | 1374 | current thread. | 
|  | 1375 |  | 
|  | 1376 | The new context is copied from a prototype context called *DefaultContext*. To | 
|  | 1377 | control the defaults so that each thread will use the same values throughout the | 
|  | 1378 | application, directly modify the *DefaultContext* object. This should be done | 
|  | 1379 | *before* any threads are started so that there won't be a race condition between | 
|  | 1380 | threads calling :func:`getcontext`. For example:: | 
|  | 1381 |  | 
|  | 1382 | # Set applicationwide defaults for all threads about to be launched | 
|  | 1383 | DefaultContext.prec = 12 | 
|  | 1384 | DefaultContext.rounding = ROUND_DOWN | 
|  | 1385 | DefaultContext.traps = ExtendedContext.traps.copy() | 
|  | 1386 | DefaultContext.traps[InvalidOperation] = 1 | 
|  | 1387 | setcontext(DefaultContext) | 
|  | 1388 |  | 
|  | 1389 | # Afterwards, the threads can be started | 
|  | 1390 | t1.start() | 
|  | 1391 | t2.start() | 
|  | 1392 | t3.start() | 
|  | 1393 | . . . | 
|  | 1394 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1395 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1396 |  | 
|  | 1397 |  | 
|  | 1398 | .. _decimal-recipes: | 
|  | 1399 |  | 
|  | 1400 | Recipes | 
|  | 1401 | ------- | 
|  | 1402 |  | 
|  | 1403 | Here are a few recipes that serve as utility functions and that demonstrate ways | 
|  | 1404 | to work with the :class:`Decimal` class:: | 
|  | 1405 |  | 
|  | 1406 | def moneyfmt(value, places=2, curr='', sep=',', dp='.', | 
|  | 1407 | pos='', neg='-', trailneg=''): | 
|  | 1408 | """Convert Decimal to a money formatted string. | 
|  | 1409 |  | 
|  | 1410 | places:  required number of places after the decimal point | 
|  | 1411 | curr:    optional currency symbol before the sign (may be blank) | 
|  | 1412 | sep:     optional grouping separator (comma, period, space, or blank) | 
|  | 1413 | dp:      decimal point indicator (comma or period) | 
|  | 1414 | only specify as blank when places is zero | 
|  | 1415 | pos:     optional sign for positive numbers: '+', space or blank | 
|  | 1416 | neg:     optional sign for negative numbers: '-', '(', space or blank | 
|  | 1417 | trailneg:optional trailing minus indicator:  '-', ')', space or blank | 
|  | 1418 |  | 
|  | 1419 | >>> d = Decimal('-1234567.8901') | 
|  | 1420 | >>> moneyfmt(d, curr='$') | 
|  | 1421 | '-$1,234,567.89' | 
|  | 1422 | >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') | 
|  | 1423 | '1.234.568-' | 
|  | 1424 | >>> moneyfmt(d, curr='$', neg='(', trailneg=')') | 
|  | 1425 | '($1,234,567.89)' | 
|  | 1426 | >>> moneyfmt(Decimal(123456789), sep=' ') | 
|  | 1427 | '123 456 789.00' | 
|  | 1428 | >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') | 
| Raymond Hettinger | 5eaffc4 | 2008-04-17 10:48:31 +0000 | [diff] [blame^] | 1429 | '<0.02>' | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1430 |  | 
|  | 1431 | """ | 
| Raymond Hettinger | 0cd7170 | 2008-02-14 12:49:37 +0000 | [diff] [blame] | 1432 | q = Decimal(10) ** -places      # 2 places --> '0.01' | 
|  | 1433 | sign, digits, exp = value.quantize(q).as_tuple() | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1434 | result = [] | 
|  | 1435 | digits = map(str, digits) | 
|  | 1436 | build, next = result.append, digits.pop | 
|  | 1437 | if sign: | 
|  | 1438 | build(trailneg) | 
|  | 1439 | for i in range(places): | 
| Raymond Hettinger | 0cd7170 | 2008-02-14 12:49:37 +0000 | [diff] [blame] | 1440 | build(next() if digits else '0') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1441 | build(dp) | 
| Raymond Hettinger | 5eaffc4 | 2008-04-17 10:48:31 +0000 | [diff] [blame^] | 1442 | if not digits: | 
|  | 1443 | build('0') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1444 | i = 0 | 
|  | 1445 | while digits: | 
|  | 1446 | build(next()) | 
|  | 1447 | i += 1 | 
|  | 1448 | if i == 3 and digits: | 
|  | 1449 | i = 0 | 
|  | 1450 | build(sep) | 
|  | 1451 | build(curr) | 
| Raymond Hettinger | 0cd7170 | 2008-02-14 12:49:37 +0000 | [diff] [blame] | 1452 | build(neg if sign else pos) | 
|  | 1453 | return ''.join(reversed(result)) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1454 |  | 
|  | 1455 | def pi(): | 
|  | 1456 | """Compute Pi to the current precision. | 
|  | 1457 |  | 
|  | 1458 | >>> print pi() | 
|  | 1459 | 3.141592653589793238462643383 | 
|  | 1460 |  | 
|  | 1461 | """ | 
|  | 1462 | getcontext().prec += 2  # extra digits for intermediate steps | 
|  | 1463 | three = Decimal(3)      # substitute "three=3.0" for regular floats | 
|  | 1464 | lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 | 
|  | 1465 | while s != lasts: | 
|  | 1466 | lasts = s | 
|  | 1467 | n, na = n+na, na+8 | 
|  | 1468 | d, da = d+da, da+32 | 
|  | 1469 | t = (t * n) / d | 
|  | 1470 | s += t | 
|  | 1471 | getcontext().prec -= 2 | 
|  | 1472 | return +s               # unary plus applies the new precision | 
|  | 1473 |  | 
|  | 1474 | def exp(x): | 
|  | 1475 | """Return e raised to the power of x.  Result type matches input type. | 
|  | 1476 |  | 
|  | 1477 | >>> print exp(Decimal(1)) | 
|  | 1478 | 2.718281828459045235360287471 | 
|  | 1479 | >>> print exp(Decimal(2)) | 
|  | 1480 | 7.389056098930650227230427461 | 
|  | 1481 | >>> print exp(2.0) | 
|  | 1482 | 7.38905609893 | 
|  | 1483 | >>> print exp(2+0j) | 
|  | 1484 | (7.38905609893+0j) | 
|  | 1485 |  | 
|  | 1486 | """ | 
|  | 1487 | getcontext().prec += 2 | 
|  | 1488 | i, lasts, s, fact, num = 0, 0, 1, 1, 1 | 
|  | 1489 | while s != lasts: | 
|  | 1490 | lasts = s | 
|  | 1491 | i += 1 | 
|  | 1492 | fact *= i | 
|  | 1493 | num *= x | 
|  | 1494 | s += num / fact | 
|  | 1495 | getcontext().prec -= 2 | 
|  | 1496 | return +s | 
|  | 1497 |  | 
|  | 1498 | def cos(x): | 
|  | 1499 | """Return the cosine of x as measured in radians. | 
|  | 1500 |  | 
|  | 1501 | >>> print cos(Decimal('0.5')) | 
|  | 1502 | 0.8775825618903727161162815826 | 
|  | 1503 | >>> print cos(0.5) | 
|  | 1504 | 0.87758256189 | 
|  | 1505 | >>> print cos(0.5+0j) | 
|  | 1506 | (0.87758256189+0j) | 
|  | 1507 |  | 
|  | 1508 | """ | 
|  | 1509 | getcontext().prec += 2 | 
|  | 1510 | i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 | 
|  | 1511 | while s != lasts: | 
|  | 1512 | lasts = s | 
|  | 1513 | i += 2 | 
|  | 1514 | fact *= i * (i-1) | 
|  | 1515 | num *= x * x | 
|  | 1516 | sign *= -1 | 
|  | 1517 | s += num / fact * sign | 
|  | 1518 | getcontext().prec -= 2 | 
|  | 1519 | return +s | 
|  | 1520 |  | 
|  | 1521 | def sin(x): | 
|  | 1522 | """Return the sine of x as measured in radians. | 
|  | 1523 |  | 
|  | 1524 | >>> print sin(Decimal('0.5')) | 
|  | 1525 | 0.4794255386042030002732879352 | 
|  | 1526 | >>> print sin(0.5) | 
|  | 1527 | 0.479425538604 | 
|  | 1528 | >>> print sin(0.5+0j) | 
|  | 1529 | (0.479425538604+0j) | 
|  | 1530 |  | 
|  | 1531 | """ | 
|  | 1532 | getcontext().prec += 2 | 
|  | 1533 | i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 | 
|  | 1534 | while s != lasts: | 
|  | 1535 | lasts = s | 
|  | 1536 | i += 2 | 
|  | 1537 | fact *= i * (i-1) | 
|  | 1538 | num *= x * x | 
|  | 1539 | sign *= -1 | 
|  | 1540 | s += num / fact * sign | 
|  | 1541 | getcontext().prec -= 2 | 
|  | 1542 | return +s | 
|  | 1543 |  | 
|  | 1544 |  | 
| Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1545 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1546 |  | 
|  | 1547 |  | 
|  | 1548 | .. _decimal-faq: | 
|  | 1549 |  | 
|  | 1550 | Decimal FAQ | 
|  | 1551 | ----------- | 
|  | 1552 |  | 
|  | 1553 | Q. It is cumbersome to type ``decimal.Decimal('1234.5')``.  Is there a way to | 
|  | 1554 | minimize typing when using the interactive interpreter? | 
|  | 1555 |  | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1556 | A. Some users abbreviate the constructor to just a single letter: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1557 |  | 
|  | 1558 | >>> D = decimal.Decimal | 
|  | 1559 | >>> D('1.23') + D('3.45') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1560 | Decimal('4.68') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1561 |  | 
|  | 1562 | Q. In a fixed-point application with two decimal places, some inputs have many | 
|  | 1563 | places and need to be rounded.  Others are not supposed to have excess digits | 
|  | 1564 | and need to be validated.  What methods should be used? | 
|  | 1565 |  | 
|  | 1566 | A. The :meth:`quantize` method rounds to a fixed number of decimal places. If | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1567 | the :const:`Inexact` trap is set, it is also useful for validation: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1568 |  | 
|  | 1569 | >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01') | 
|  | 1570 |  | 
|  | 1571 | >>> # Round to two places | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1572 | >>> Decimal('3.214').quantize(TWOPLACES) | 
|  | 1573 | Decimal('3.21') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1574 |  | 
|  | 1575 | >>> # Validate that a number does not exceed two places | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1576 | >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) | 
|  | 1577 | Decimal('3.21') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1578 |  | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1579 | >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1580 | Traceback (most recent call last): | 
|  | 1581 | ... | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1582 | Inexact | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1583 |  | 
|  | 1584 | Q. Once I have valid two place inputs, how do I maintain that invariant | 
|  | 1585 | throughout an application? | 
|  | 1586 |  | 
| Raymond Hettinger | 4631481 | 2008-02-14 10:46:57 +0000 | [diff] [blame] | 1587 | A. Some operations like addition, subtraction, and multiplication by an integer | 
|  | 1588 | will automatically preserve fixed point.  Others operations, like division and | 
|  | 1589 | non-integer multiplication, will change the number of decimal places and need to | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1590 | be followed-up with a :meth:`quantize` step: | 
| Raymond Hettinger | 4631481 | 2008-02-14 10:46:57 +0000 | [diff] [blame] | 1591 |  | 
|  | 1592 | >>> a = Decimal('102.72')           # Initial fixed-point values | 
|  | 1593 | >>> b = Decimal('3.17') | 
|  | 1594 | >>> a + b                           # Addition preserves fixed-point | 
|  | 1595 | Decimal('105.89') | 
|  | 1596 | >>> a - b | 
|  | 1597 | Decimal('99.55') | 
|  | 1598 | >>> a * 42                          # So does integer multiplication | 
|  | 1599 | Decimal('4314.24') | 
|  | 1600 | >>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication | 
|  | 1601 | Decimal('325.62') | 
| Raymond Hettinger | 27a90d9 | 2008-02-14 11:01:10 +0000 | [diff] [blame] | 1602 | >>> (b / a).quantize(TWOPLACES)     # And quantize division | 
| Raymond Hettinger | 4631481 | 2008-02-14 10:46:57 +0000 | [diff] [blame] | 1603 | Decimal('0.03') | 
|  | 1604 |  | 
|  | 1605 | In developing fixed-point applications, it is convenient to define functions | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1606 | to handle the :meth:`quantize` step: | 
| Raymond Hettinger | 4631481 | 2008-02-14 10:46:57 +0000 | [diff] [blame] | 1607 |  | 
| Raymond Hettinger | 27a90d9 | 2008-02-14 11:01:10 +0000 | [diff] [blame] | 1608 | >>> def mul(x, y, fp=TWOPLACES): | 
|  | 1609 | ...     return (x * y).quantize(fp) | 
|  | 1610 | >>> def div(x, y, fp=TWOPLACES): | 
|  | 1611 | ...     return (x / y).quantize(fp) | 
| Raymond Hettinger | d68bf02 | 2008-02-14 11:57:25 +0000 | [diff] [blame] | 1612 |  | 
| Raymond Hettinger | 4631481 | 2008-02-14 10:46:57 +0000 | [diff] [blame] | 1613 | >>> mul(a, b)                       # Automatically preserve fixed-point | 
|  | 1614 | Decimal('325.62') | 
|  | 1615 | >>> div(b, a) | 
|  | 1616 | Decimal('0.03') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1617 |  | 
|  | 1618 | Q. There are many ways to express the same value.  The numbers :const:`200`, | 
|  | 1619 | :const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at | 
|  | 1620 | various precisions. Is there a way to transform them to a single recognizable | 
|  | 1621 | canonical value? | 
|  | 1622 |  | 
|  | 1623 | A. The :meth:`normalize` method maps all equivalent values to a single | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1624 | representative: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1625 |  | 
|  | 1626 | >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) | 
|  | 1627 | >>> [v.normalize() for v in values] | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1628 | [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')] | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1629 |  | 
|  | 1630 | Q. Some decimal values always print with exponential notation.  Is there a way | 
|  | 1631 | to get a non-exponential representation? | 
|  | 1632 |  | 
|  | 1633 | A. For some values, exponential notation is the only way to express the number | 
|  | 1634 | of significant places in the coefficient.  For example, expressing | 
|  | 1635 | :const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the | 
|  | 1636 | original's two-place significance. | 
|  | 1637 |  | 
| Raymond Hettinger | d68bf02 | 2008-02-14 11:57:25 +0000 | [diff] [blame] | 1638 | If an application does not care about tracking significance, it is easy to | 
| Georg Brandl | 907a720 | 2008-02-22 12:31:45 +0000 | [diff] [blame] | 1639 | remove the exponent and trailing zeroes, losing significance, but keeping the | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1640 | value unchanged: | 
| Raymond Hettinger | d68bf02 | 2008-02-14 11:57:25 +0000 | [diff] [blame] | 1641 |  | 
|  | 1642 | >>> def remove_exponent(d): | 
|  | 1643 | ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() | 
|  | 1644 |  | 
|  | 1645 | >>> remove_exponent(Decimal('5E+3')) | 
|  | 1646 | Decimal('5000') | 
|  | 1647 |  | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1648 | Q. Is there a way to convert a regular float to a :class:`Decimal`? | 
|  | 1649 |  | 
|  | 1650 | A. Yes, all binary floating point numbers can be exactly expressed as a | 
|  | 1651 | Decimal.  An exact conversion may take more precision than intuition would | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1652 | suggest, so we trap :const:`Inexact` to signal a need for more precision: | 
|  | 1653 |  | 
| Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 1654 | .. testcode:: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1655 |  | 
| Raymond Hettinger | ff1f973 | 2008-02-07 20:04:37 +0000 | [diff] [blame] | 1656 | def float_to_decimal(f): | 
|  | 1657 | "Convert a floating point number to a Decimal with no loss of information" | 
|  | 1658 | n, d = f.as_integer_ratio() | 
|  | 1659 | with localcontext() as ctx: | 
|  | 1660 | ctx.traps[Inexact] = True | 
|  | 1661 | while True: | 
|  | 1662 | try: | 
|  | 1663 | return Decimal(n) / Decimal(d) | 
|  | 1664 | except Inexact: | 
|  | 1665 | ctx.prec += 1 | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1666 |  | 
| Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 1667 | .. doctest:: | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1668 |  | 
| Raymond Hettinger | ff1f973 | 2008-02-07 20:04:37 +0000 | [diff] [blame] | 1669 | >>> float_to_decimal(math.pi) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1670 | Decimal('3.141592653589793115997963468544185161590576171875') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1671 |  | 
| Raymond Hettinger | 23bdcc9 | 2008-02-07 20:10:49 +0000 | [diff] [blame] | 1672 | Q. Why isn't the :func:`float_to_decimal` routine included in the module? | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1673 |  | 
|  | 1674 | A. There is some question about whether it is advisable to mix binary and | 
|  | 1675 | decimal floating point.  Also, its use requires some care to avoid the | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1676 | representation issues associated with binary floating point: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1677 |  | 
| Raymond Hettinger | 23bdcc9 | 2008-02-07 20:10:49 +0000 | [diff] [blame] | 1678 | >>> float_to_decimal(1.1) | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1679 | Decimal('1.100000000000000088817841970012523233890533447265625') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1680 |  | 
|  | 1681 | Q. Within a complex calculation, how can I make sure that I haven't gotten a | 
|  | 1682 | spurious result because of insufficient precision or rounding anomalies. | 
|  | 1683 |  | 
|  | 1684 | A. The decimal module makes it easy to test results.  A best practice is to | 
|  | 1685 | re-run calculations using greater precision and with various rounding modes. | 
|  | 1686 | Widely differing results indicate insufficient precision, rounding mode issues, | 
|  | 1687 | ill-conditioned inputs, or a numerically unstable algorithm. | 
|  | 1688 |  | 
|  | 1689 | Q. I noticed that context precision is applied to the results of operations but | 
|  | 1690 | not to the inputs.  Is there anything to watch out for when mixing values of | 
|  | 1691 | different precisions? | 
|  | 1692 |  | 
|  | 1693 | A. Yes.  The principle is that all values are considered to be exact and so is | 
|  | 1694 | the arithmetic on those values.  Only the results are rounded.  The advantage | 
|  | 1695 | for inputs is that "what you type is what you get".  A disadvantage is that the | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1696 | results can look odd if you forget that the inputs haven't been rounded: | 
|  | 1697 |  | 
|  | 1698 | .. doctest:: newcontext | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1699 |  | 
|  | 1700 | >>> getcontext().prec = 3 | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1701 | >>> Decimal('3.104') + Decimal('2.104') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1702 | Decimal('5.21') | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1703 | >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1704 | Decimal('5.20') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1705 |  | 
|  | 1706 | The solution is either to increase precision or to force rounding of inputs | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1707 | using the unary plus operation: | 
|  | 1708 |  | 
|  | 1709 | .. doctest:: newcontext | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1710 |  | 
|  | 1711 | >>> getcontext().prec = 3 | 
|  | 1712 | >>> +Decimal('1.23456789')      # unary plus triggers rounding | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1713 | Decimal('1.23') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1714 |  | 
|  | 1715 | Alternatively, inputs can be rounded upon creation using the | 
| Georg Brandl | 9f66232 | 2008-03-22 11:47:10 +0000 | [diff] [blame] | 1716 | :meth:`Context.create_decimal` method: | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1717 |  | 
|  | 1718 | >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') | 
| Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1719 | Decimal('1.2345') | 
| Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1720 |  |