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