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