~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-2.7.12-docs-html/_sources/library/decimal.txt

  • Committer: Dave Kuhlman
  • Date: 2017-04-15 16:24:56 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20170415162456-iav9vozzg4iwqwv3
Updated docs

Show diffs side-by-side

added added

removed removed

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