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