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