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