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