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