decimal.rst 72.5 KB
Newer Older
Christian Heimes's avatar
Christian Heimes committed
1 2
:mod:`decimal` --- Decimal fixed point and floating point arithmetic
====================================================================
3 4 5 6 7 8 9 10 11

.. module:: decimal
   :synopsis: Implementation of the General Decimal Arithmetic  Specification.

.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
.. moduleauthor:: Raymond Hettinger <python at rcn.com>
.. moduleauthor:: Aahz <aahz at pobox.com>
.. moduleauthor:: Tim Peters <tim.one at comcast.net>
12
.. moduleauthor:: Stefan Krah <skrah at bytereef.org>
13 14
.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>

Christian Heimes's avatar
Christian Heimes committed
15 16 17 18 19 20 21 22
.. import modules for testing inline doctests with the Sphinx doctest builder
.. testsetup:: *

   import decimal
   import math
   from decimal import *
   # make sure each group gets a fresh context
   setcontext(Context())
23

24 25 26
The :mod:`decimal` module provides support for fast correctly-rounded
decimal floating point arithmetic. It offers several advantages over the
:class:`float` datatype:
27

Christian Heimes's avatar
Christian Heimes committed
28 29 30 31 32
* Decimal "is based on a floating-point model which was designed with people
  in mind, and necessarily has a paramount guiding principle -- computers must
  provide an arithmetic that works in the same way as the arithmetic that
  people learn at school." -- excerpt from the decimal arithmetic specification.

33
* Decimal numbers can be represented exactly.  In contrast, numbers like
Terry Jan Reedy's avatar
Terry Jan Reedy committed
34
  :const:`1.1` and :const:`2.2` do not have exact representations in binary
35 36
  floating point. End users typically would not expect ``1.1 + 2.2`` to display
  as :const:`3.3000000000000003` as it does with binary floating point.
37 38

* The exactness carries over into arithmetic.  In decimal floating point, ``0.1
39
  + 0.1 + 0.1 - 0.3`` is exactly equal to zero.  In binary floating point, the result
40 41
  is :const:`5.5511151231257827e-017`.  While near to zero, the differences
  prevent reliable equality testing and differences can accumulate. For this
Christian Heimes's avatar
Christian Heimes committed
42
  reason, decimal is preferred in accounting applications which have strict
43 44 45 46 47 48 49 50 51 52
  equality invariants.

* The decimal module incorporates a notion of significant places so that ``1.30
  + 1.20`` is :const:`2.50`.  The trailing zero is kept to indicate significance.
  This is the customary presentation for monetary applications. For
  multiplication, the "schoolbook" approach uses all the figures in the
  multiplicands.  For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
  1.20`` gives :const:`1.5600`.

* Unlike hardware based binary floating point, the decimal module has a user
53
  alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimes's avatar
Christian Heimes committed
54
  a given problem:
55

56
     >>> from decimal import *
57 58
     >>> getcontext().prec = 6
     >>> Decimal(1) / Decimal(7)
Christian Heimes's avatar
Christian Heimes committed
59
     Decimal('0.142857')
60 61
     >>> getcontext().prec = 28
     >>> Decimal(1) / Decimal(7)
Christian Heimes's avatar
Christian Heimes committed
62
     Decimal('0.1428571428571428571428571429')
63 64 65 66 67

* Both binary and decimal floating point are implemented in terms of published
  standards.  While the built-in float type exposes only a modest portion of its
  capabilities, the decimal module exposes all required parts of the standard.
  When needed, the programmer has full control over rounding and signal handling.
Christian Heimes's avatar
Christian Heimes committed
68 69 70 71 72 73 74
  This includes an option to enforce exact arithmetic by using exceptions
  to block any inexact operations.

* The decimal module was designed to support "without prejudice, both exact
  unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
  and rounded floating-point arithmetic."  -- excerpt from the decimal
  arithmetic specification.
75 76 77 78 79 80

The module design is centered around three concepts:  the decimal number, the
context for arithmetic, and signals.

A decimal number is immutable.  It has a sign, coefficient digits, and an
exponent.  To preserve significance, the coefficient digits do not truncate
81
trailing zeros.  Decimals also include special values such as
82 83 84 85 86 87 88 89
:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`.  The standard also
differentiates :const:`-0` from :const:`+0`.

The context for arithmetic is an environment specifying precision, rounding
rules, limits on exponents, flags indicating the results of operations, and trap
enablers which determine whether signals are treated as exceptions.  Rounding
options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
90
:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
91 92 93 94 95 96

Signals are groups of exceptional conditions arising during the course of
computation.  Depending on the needs of the application, signals may be ignored,
considered as informational, or treated as exceptions. The signals in the
decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
97
:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`.
98 99

For each signal there is a flag and a trap enabler.  When a signal is
100
encountered, its flag is set to one, then, if the trap enabler is
101 102 103 104 105 106
set to one, an exception is raised.  Flags are sticky, so the user needs to
reset them before monitoring a calculation.


.. seealso::

107
   * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
108
     Specification <http://speleotrove.com/decimal/decarith.html>`_.
109

110
   * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes's avatar
Christian Heimes committed
111
     <http://754r.ucbtest.org/standards/854.pdf>`_.
112

113
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 115 116 117 118 119 120 121 122 123 124 125 126


.. _decimal-tutorial:

Quick-start Tutorial
--------------------

The usual start to using decimals is importing the module, viewing the current
context with :func:`getcontext` and, if necessary, setting new values for
precision, rounding, or enabled traps::

   >>> from decimal import *
   >>> getcontext()
127
   Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
128
           capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimes's avatar
Christian Heimes committed
129
           InvalidOperation])
130 131 132

   >>> getcontext().prec = 7       # Set a new precision

133 134 135
Decimal instances can be constructed from integers, strings, floats, or tuples.
Construction from an integer or a float performs an exact conversion of the
value of that integer or float.  Decimal numbers include special values such as
136
:const:`NaN` which stands for "Not a number", positive and negative
137
:const:`Infinity`, and :const:`-0`::
138

139
   >>> getcontext().prec = 28
140
   >>> Decimal(10)
Christian Heimes's avatar
Christian Heimes committed
141 142 143
   Decimal('10')
   >>> Decimal('3.14')
   Decimal('3.14')
144 145
   >>> Decimal(3.14)
   Decimal('3.140000000000000124344978758017532527446746826171875')
146
   >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes's avatar
Christian Heimes committed
147
   Decimal('3.14')
148
   >>> Decimal(str(2.0 ** 0.5))
149
   Decimal('1.4142135623730951')
Christian Heimes's avatar
Christian Heimes committed
150 151 152 153 154 155
   >>> Decimal(2) ** Decimal('0.5')
   Decimal('1.414213562373095048801688724')
   >>> Decimal('NaN')
   Decimal('NaN')
   >>> Decimal('-Infinity')
   Decimal('-Infinity')
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
If the :exc:`FloatOperation` signal is trapped, accidental mixing of
decimals and floats in constructors or ordering comparisons raises
an exception::

   >>> c = getcontext()
   >>> c.traps[FloatOperation] = True
   >>> Decimal(3.14)
   Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
   >>> Decimal('3.5') < 3.7
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
   >>> Decimal('3.5') == 3.5
   True

.. versionadded:: 3.3

176 177
The significance of a new Decimal is determined solely by the number of digits
input.  Context precision and rounding only come into play during arithmetic
Christian Heimes's avatar
Christian Heimes committed
178 179 180
operations.

.. doctest:: newcontext
181 182 183

   >>> getcontext().prec = 6
   >>> Decimal('3.0')
Christian Heimes's avatar
Christian Heimes committed
184
   Decimal('3.0')
185
   >>> Decimal('3.1415926535')
Christian Heimes's avatar
Christian Heimes committed
186
   Decimal('3.1415926535')
187
   >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes's avatar
Christian Heimes committed
188
   Decimal('5.85987')
189 190
   >>> getcontext().rounding = ROUND_UP
   >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes's avatar
Christian Heimes committed
191
   Decimal('5.85988')
192

193 194 195 196 197 198 199 200 201 202
If the internal limits of the C version are exceeded, constructing
a decimal raises :class:`InvalidOperation`::

   >>> Decimal("1e9999999999999999999")
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

.. versionchanged:: 3.3

203
Decimals interact well with much of the rest of Python.  Here is a small decimal
Christian Heimes's avatar
Christian Heimes committed
204 205 206 207
floating point flying circus:

.. doctest::
   :options: +NORMALIZE_WHITESPACE
208

209
   >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
210
   >>> max(data)
Christian Heimes's avatar
Christian Heimes committed
211
   Decimal('9.25')
212
   >>> min(data)
Christian Heimes's avatar
Christian Heimes committed
213
   Decimal('0.03')
214
   >>> sorted(data)
Christian Heimes's avatar
Christian Heimes committed
215 216
   [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
    Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
217
   >>> sum(data)
Christian Heimes's avatar
Christian Heimes committed
218
   Decimal('19.29')
219 220 221 222
   >>> a,b,c = data[:3]
   >>> str(a)
   '1.34'
   >>> float(a)
223 224 225
   1.34
   >>> round(a, 1)
   Decimal('1.3')
226 227 228
   >>> int(a)
   1
   >>> a * 5
Christian Heimes's avatar
Christian Heimes committed
229
   Decimal('6.70')
230
   >>> a * b
Christian Heimes's avatar
Christian Heimes committed
231
   Decimal('2.5058')
232
   >>> c % a
Christian Heimes's avatar
Christian Heimes committed
233
   Decimal('0.77')
234

Christian Heimes's avatar
Christian Heimes committed
235
And some mathematical functions are also available to Decimal:
236

237
   >>> getcontext().prec = 28
238
   >>> Decimal(2).sqrt()
Christian Heimes's avatar
Christian Heimes committed
239
   Decimal('1.414213562373095048801688724')
240
   >>> Decimal(1).exp()
Christian Heimes's avatar
Christian Heimes committed
241 242 243 244 245
   Decimal('2.718281828459045235360287471')
   >>> Decimal('10').ln()
   Decimal('2.302585092994045684017991455')
   >>> Decimal('10').log10()
   Decimal('1')
246

247 248
The :meth:`quantize` method rounds a number to a fixed exponent.  This method is
useful for monetary applications that often round results to a fixed number of
Christian Heimes's avatar
Christian Heimes committed
249
places:
250 251

   >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes's avatar
Christian Heimes committed
252
   Decimal('7.32')
253
   >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes's avatar
Christian Heimes committed
254
   Decimal('8')
255 256 257 258 259 260 261 262 263

As shown above, the :func:`getcontext` function accesses the current context and
allows the settings to be changed.  This approach meets the needs of most
applications.

For more advanced work, it may be useful to create alternate contexts using the
Context() constructor.  To make an alternate active, use the :func:`setcontext`
function.

264
In accordance with the standard, the :mod:`decimal` module provides two ready to
265 266
use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
former is especially useful for debugging because many of the traps are
Christian Heimes's avatar
Christian Heimes committed
267 268 269 270
enabled:

.. doctest:: newcontext
   :options: +NORMALIZE_WHITESPACE
271 272 273 274

   >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
   >>> setcontext(myothercontext)
   >>> Decimal(1) / Decimal(7)
Christian Heimes's avatar
Christian Heimes committed
275
   Decimal('0.142857142857142857142857142857142857142857142857142857142857')
276 277

   >>> ExtendedContext
278
   Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
279
           capitals=1, clamp=0, flags=[], traps=[])
280 281
   >>> setcontext(ExtendedContext)
   >>> Decimal(1) / Decimal(7)
Christian Heimes's avatar
Christian Heimes committed
282
   Decimal('0.142857143')
283
   >>> Decimal(42) / Decimal(0)
Christian Heimes's avatar
Christian Heimes committed
284
   Decimal('Infinity')
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

   >>> setcontext(BasicContext)
   >>> Decimal(42) / Decimal(0)
   Traceback (most recent call last):
     File "<pyshell#143>", line 1, in -toplevel-
       Decimal(42) / Decimal(0)
   DivisionByZero: x / 0

Contexts also have signal flags for monitoring exceptional conditions
encountered during computations.  The flags remain set until explicitly cleared,
so it is best to clear the flags before each set of monitored computations by
using the :meth:`clear_flags` method. ::

   >>> setcontext(ExtendedContext)
   >>> getcontext().clear_flags()
   >>> Decimal(355) / Decimal(113)
Christian Heimes's avatar
Christian Heimes committed
301
   Decimal('3.14159292')
302
   >>> getcontext()
303
   Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
304
           capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
305 306 307 308 309 310

The *flags* entry shows that the rational approximation to :const:`Pi` was
rounded (digits beyond the context precision were thrown away) and that the
result is inexact (some of the discarded digits were non-zero).

Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimes's avatar
Christian Heimes committed
311
context:
312

Christian Heimes's avatar
Christian Heimes committed
313 314 315
.. doctest:: newcontext

   >>> setcontext(ExtendedContext)
316
   >>> Decimal(1) / Decimal(0)
Christian Heimes's avatar
Christian Heimes committed
317
   Decimal('Infinity')
318 319 320 321 322 323 324 325 326 327 328 329 330
   >>> getcontext().traps[DivisionByZero] = 1
   >>> Decimal(1) / Decimal(0)
   Traceback (most recent call last):
     File "<pyshell#112>", line 1, in -toplevel-
       Decimal(1) / Decimal(0)
   DivisionByZero: x / 0

Most programs adjust the current context only once, at the beginning of the
program.  And, in many applications, data is converted to :class:`Decimal` with
a single cast inside a loop.  With context set and decimals created, the bulk of
the program manipulates the data no differently than with other Python numeric
types.

331
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
332 333 334 335 336 337 338 339


.. _decimal-decimal:

Decimal objects
---------------


340
.. class:: Decimal(value="0", context=None)
341

342
   Construct a new :class:`Decimal` object based from *value*.
343

344
   *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes's avatar
Christian Heimes committed
345
   object. If no *value* is given, returns ``Decimal('0')``.  If *value* is a
346 347
   string, it should conform to the decimal numeric string syntax after leading
   and trailing whitespace characters are removed::
348 349 350 351 352 353 354 355 356 357

      sign           ::=  '+' | '-'
      digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
      indicator      ::=  'e' | 'E'
      digits         ::=  digit [digit]...
      decimal-part   ::=  digits '.' [digits] | ['.'] digits
      exponent-part  ::=  indicator [sign] digits
      infinity       ::=  'Infinity' | 'Inf'
      nan            ::=  'NaN' [digits] | 'sNaN' [digits]
      numeric-value  ::=  decimal-part [exponent-part] | infinity
358
      numeric-string ::=  [sign] numeric-value | [sign] nan
359

360 361 362 363 364
   Other Unicode decimal digits are also permitted where ``digit``
   appears above.  These include decimal digits from various other
   alphabets (for example, Arabic-Indic and Devanāgarī digits) along
   with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.

365 366 367
   If *value* is a :class:`tuple`, it should have three components, a sign
   (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
   digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes's avatar
Christian Heimes committed
368
   returns ``Decimal('1.414')``.
369

370 371
   If *value* is a :class:`float`, the binary floating point value is losslessly
   converted to its exact decimal equivalent.  This conversion can often require
372 373 374
   53 or more digits of precision.  For example, ``Decimal(float('1.1'))``
   converts to
   ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
375

376 377
   The *context* precision does not affect how many digits are stored. That is
   determined exclusively by the number of digits in *value*. For example,
Christian Heimes's avatar
Christian Heimes committed
378
   ``Decimal('3.00000')`` records all five zeros even if the context precision is
379 380 381 382 383 384 385 386 387
   only three.

   The purpose of the *context* argument is determining what to do if *value* is a
   malformed string.  If the context traps :const:`InvalidOperation`, an exception
   is raised; otherwise, the constructor returns a new Decimal with the value of
   :const:`NaN`.

   Once constructed, :class:`Decimal` objects are immutable.

388
   .. versionchanged:: 3.2
389 390
      The argument to the constructor is now permitted to be a :class:`float`
      instance.
391

392 393 394 395
   .. versionchanged:: 3.3
      :class:`float` arguments raise an exception if the :exc:`FloatOperation`
      trap is set. By default the trap is off.

396 397 398 399 400
   Decimal floating point objects share many properties with the other built-in
   numeric types such as :class:`float` and :class:`int`.  All of the usual math
   operations and special methods apply.  Likewise, decimal objects can be
   copied, pickled, printed, used as dictionary keys, used as set elements,
   compared, sorted, and coerced to another type (such as :class:`float` or
401
   :class:`int`).
402

403 404 405 406 407 408 409 410 411 412 413 414
   There are some small differences between arithmetic on Decimal objects and
   arithmetic on integers and floats.  When the remainder operator ``%`` is
   applied to Decimal objects, the sign of the result is the sign of the
   *dividend* rather than the sign of the divisor::

      >>> (-7) % 4
      1
      >>> Decimal(-7) % Decimal(4)
      Decimal('-3')

   The integer division operator ``//`` behaves analogously, returning the
   integer part of the true quotient (truncating towards zero) rather than its
Mark Dickinson's avatar
Mark Dickinson committed
415
   floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::
416 417 418 419 420 421 422 423 424 425

      >>> -7 // 4
      -2
      >>> Decimal(-7) // Decimal(4)
      Decimal('-1')

   The ``%`` and ``//`` operators implement the ``remainder`` and
   ``divide-integer`` operations (respectively) as described in the
   specification.

426 427 428 429 430 431 432
   Decimal objects cannot generally be combined with floats or
   instances of :class:`fractions.Fraction` in arithmetic operations:
   an attempt to add a :class:`Decimal` to a :class:`float`, for
   example, will raise a :exc:`TypeError`.  However, it is possible to
   use Python's comparison operators to compare a :class:`Decimal`
   instance ``x`` with another number ``y``.  This avoids confusing results
   when doing equality comparisons between numbers of different types.
433

434
   .. versionchanged:: 3.2
435 436
      Mixed-type comparisons between :class:`Decimal` instances and other
      numeric types are now fully supported.
437

438 439
   In addition to the standard numeric properties, decimal floating point
   objects also have a number of specialized methods:
440 441


442
   .. method:: adjusted()
443

444 445 446 447
      Return the adjusted exponent after shifting out the coefficient's
      rightmost digits until only the lead digit remains:
      ``Decimal('321e+5').adjusted()`` returns seven.  Used for determining the
      position of the most significant digit with respect to the decimal point.
448 449


450
   .. method:: as_tuple()
451

452 453
      Return a :term:`named tuple` representation of the number:
      ``DecimalTuple(sign, digits, exponent)``.
454

455

456
   .. method:: canonical()
457

458 459 460
      Return the canonical encoding of the argument.  Currently, the encoding of
      a :class:`Decimal` instance is always canonical, so this operation returns
      its argument unchanged.
461

462
   .. method:: compare(other, context=None)
463

464 465 466 467 468 469 470 471
      Compare the values of two Decimal instances.  :meth:`compare` returns a
      Decimal instance, and if either operand is a NaN then the result is a
      NaN::

         a or b is a NaN  ==> Decimal('NaN')
         a < b            ==> Decimal('-1')
         a == b           ==> Decimal('0')
         a > b            ==> Decimal('1')
472

473
   .. method:: compare_signal(other, context=None)
474

475 476 477
      This operation is identical to the :meth:`compare` method, except that all
      NaNs signal.  That is, if neither operand is a signaling NaN then any
      quiet NaN operand is treated as though it were a signaling NaN.
478

479
   .. method:: compare_total(other, context=None)
480

481 482 483 484 485
      Compare two operands using their abstract representation rather than their
      numerical value.  Similar to the :meth:`compare` method, but the result
      gives a total ordering on :class:`Decimal` instances.  Two
      :class:`Decimal` instances with the same numeric value but different
      representations compare unequal in this ordering:
486

487 488
         >>> Decimal('12.0').compare_total(Decimal('12'))
         Decimal('-1')
489

490 491 492 493 494 495
      Quiet and signaling NaNs are also included in the total ordering.  The
      result of this function is ``Decimal('0')`` if both operands have the same
      representation, ``Decimal('-1')`` if the first operand is lower in the
      total order than the second, and ``Decimal('1')`` if the first operand is
      higher in the total order than the second operand.  See the specification
      for details of the total order.
496

497 498 499 500 501
      This operation is unaffected by context and is quiet: no flags are changed
      and no rounding is performed.  As an exception, the C version may raise
      InvalidOperation if the second operand cannot be converted exactly.

   .. method:: compare_total_mag(other, context=None)
502

503 504 505 506
      Compare two operands using their abstract representation rather than their
      value as in :meth:`compare_total`, but ignoring the sign of each operand.
      ``x.compare_total_mag(y)`` is equivalent to
      ``x.copy_abs().compare_total(y.copy_abs())``.
507

508 509 510 511
      This operation is unaffected by context and is quiet: no flags are changed
      and no rounding is performed.  As an exception, the C version may raise
      InvalidOperation if the second operand cannot be converted exactly.

512 513
   .. method:: conjugate()

Benjamin Peterson's avatar
Benjamin Peterson committed
514
      Just returns self, this method is only to comply with the Decimal
515 516
      Specification.

517
   .. method:: copy_abs()
518

519 520 521
      Return the absolute value of the argument.  This operation is unaffected
      by the context and is quiet: no flags are changed and no rounding is
      performed.
522

523
   .. method:: copy_negate()
524

525 526
      Return the negation of the argument.  This operation is unaffected by the
      context and is quiet: no flags are changed and no rounding is performed.
527

528
   .. method:: copy_sign(other, context=None)
529

530 531
      Return a copy of the first operand with the sign set to be the same as the
      sign of the second operand.  For example:
532

533 534
         >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
         Decimal('-2.3')
535

536 537 538
      This operation is unaffected by context and is quiet: no flags are changed
      and no rounding is performed.  As an exception, the C version may raise
      InvalidOperation if the second operand cannot be converted exactly.
539

540
   .. method:: exp(context=None)
541

542 543 544
      Return the value of the (natural) exponential function ``e**x`` at the
      given number.  The result is correctly rounded using the
      :const:`ROUND_HALF_EVEN` rounding mode.
545

546 547 548 549
      >>> Decimal(1).exp()
      Decimal('2.718281828459045235360287471')
      >>> Decimal(321).exp()
      Decimal('2.561702493119680037517373933E+139')
550

551 552 553 554 555 556 557 558 559 560
   .. method:: from_float(f)

      Classmethod that converts a float to a decimal number, exactly.

      Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
      Since 0.1 is not exactly representable in binary floating point, the
      value is stored as the nearest representable value which is
      `0x1.999999999999ap-4`.  That equivalent value in decimal is
      `0.1000000000000000055511151231257827021181583404541015625`.

561 562 563
      .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
         can also be constructed directly from a :class:`float`.

564 565 566 567 568 569 570 571 572 573 574
      .. doctest::

          >>> Decimal.from_float(0.1)
          Decimal('0.1000000000000000055511151231257827021181583404541015625')
          >>> Decimal.from_float(float('nan'))
          Decimal('NaN')
          >>> Decimal.from_float(float('inf'))
          Decimal('Infinity')
          >>> Decimal.from_float(float('-inf'))
          Decimal('-Infinity')

575
      .. versionadded:: 3.1
576

577
   .. method:: fma(other, third, context=None)
578

579 580
      Fused multiply-add.  Return self*other+third with no rounding of the
      intermediate product self*other.
581

582 583
      >>> Decimal(2).fma(3, 5)
      Decimal('11')
584

585
   .. method:: is_canonical()
586

587 588 589
      Return :const:`True` if the argument is canonical and :const:`False`
      otherwise.  Currently, a :class:`Decimal` instance is always canonical, so
      this operation always returns :const:`True`.
590

591
   .. method:: is_finite()
592

593 594
      Return :const:`True` if the argument is a finite number, and
      :const:`False` if the argument is an infinity or a NaN.
595

596
   .. method:: is_infinite()
597

598 599
      Return :const:`True` if the argument is either positive or negative
      infinity and :const:`False` otherwise.
600

601
   .. method:: is_nan()
602

603 604
      Return :const:`True` if the argument is a (quiet or signaling) NaN and
      :const:`False` otherwise.
605

606
   .. method:: is_normal(context=None)
607

608 609
      Return :const:`True` if the argument is a *normal* finite number.  Return
      :const:`False` if the argument is zero, subnormal, infinite or a NaN.
610

611
   .. method:: is_qnan()
612

613 614
      Return :const:`True` if the argument is a quiet NaN, and
      :const:`False` otherwise.
615

616
   .. method:: is_signed()
617

618 619
      Return :const:`True` if the argument has a negative sign and
      :const:`False` otherwise.  Note that zeros and NaNs can both carry signs.
620

621
   .. method:: is_snan()
622

623 624
      Return :const:`True` if the argument is a signaling NaN and :const:`False`
      otherwise.
625

626
   .. method:: is_subnormal(context=None)
627

628 629
      Return :const:`True` if the argument is subnormal, and :const:`False`
      otherwise.
630

631
   .. method:: is_zero()
632

633 634
      Return :const:`True` if the argument is a (positive or negative) zero and
      :const:`False` otherwise.
635

636
   .. method:: ln(context=None)
637

638 639
      Return the natural (base e) logarithm of the operand.  The result is
      correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
640

641
   .. method:: log10(context=None)
642

643 644
      Return the base ten logarithm of the operand.  The result is correctly
      rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
645

646
   .. method:: logb(context=None)
647

648 649 650 651 652
      For a nonzero number, return the adjusted exponent of its operand as a
      :class:`Decimal` instance.  If the operand is a zero then
      ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
      is raised.  If the operand is an infinity then ``Decimal('Infinity')`` is
      returned.
653

654
   .. method:: logical_and(other, context=None)
655

656 657 658
      :meth:`logical_and` is a logical operation which takes two *logical
      operands* (see :ref:`logical_operands_label`).  The result is the
      digit-wise ``and`` of the two operands.
659

660
   .. method:: logical_invert(context=None)
661

662
      :meth:`logical_invert` is a logical operation.  The
663
      result is the digit-wise inversion of the operand.
664

665
   .. method:: logical_or(other, context=None)
666

667 668 669
      :meth:`logical_or` is a logical operation which takes two *logical
      operands* (see :ref:`logical_operands_label`).  The result is the
      digit-wise ``or`` of the two operands.
670

671
   .. method:: logical_xor(other, context=None)
672

673 674 675
      :meth:`logical_xor` is a logical operation which takes two *logical
      operands* (see :ref:`logical_operands_label`).  The result is the
      digit-wise exclusive or of the two operands.
676

677
   .. method:: max(other, context=None)
678

679 680 681 682
      Like ``max(self, other)`` except that the context rounding rule is applied
      before returning and that :const:`NaN` values are either signaled or
      ignored (depending on the context and whether they are signaling or
      quiet).
683

684
   .. method:: max_mag(other, context=None)
685

686
      Similar to the :meth:`.max` method, but the comparison is done using the
687
      absolute values of the operands.
688

689
   .. method:: min(other, context=None)
690

691 692 693 694
      Like ``min(self, other)`` except that the context rounding rule is applied
      before returning and that :const:`NaN` values are either signaled or
      ignored (depending on the context and whether they are signaling or
      quiet).
695

696
   .. method:: min_mag(other, context=None)
697

698
      Similar to the :meth:`.min` method, but the comparison is done using the
699
      absolute values of the operands.
700

701
   .. method:: next_minus(context=None)
702

703 704 705
      Return the largest number representable in the given context (or in the
      current thread's context if no context is given) that is smaller than the
      given operand.
706

707
   .. method:: next_plus(context=None)
708

709 710 711
      Return the smallest number representable in the given context (or in the
      current thread's context if no context is given) that is larger than the
      given operand.
712

713
   .. method:: next_toward(other, context=None)
714

715 716 717 718
      If the two operands are unequal, return the number closest to the first
      operand in the direction of the second operand.  If both operands are
      numerically equal, return a copy of the first operand with the sign set to
      be the same as the sign of the second operand.
719

720
   .. method:: normalize(context=None)
721

722 723
      Normalize the number by stripping the rightmost trailing zeros and
      converting any result equal to :const:`Decimal('0')` to
724
      :const:`Decimal('0e0')`. Used for producing canonical values for attributes
725 726 727
      of an equivalence class. For example, ``Decimal('32.100')`` and
      ``Decimal('0.321000e+2')`` both normalize to the equivalent value
      ``Decimal('32.1')``.
728

729
   .. method:: number_class(context=None)
730

731 732
      Return a string describing the *class* of the operand.  The returned value
      is one of the following ten strings.
733

734 735 736 737 738 739 740 741 742 743
      * ``"-Infinity"``, indicating that the operand is negative infinity.
      * ``"-Normal"``, indicating that the operand is a negative normal number.
      * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
      * ``"-Zero"``, indicating that the operand is a negative zero.
      * ``"+Zero"``, indicating that the operand is a positive zero.
      * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
      * ``"+Normal"``, indicating that the operand is a positive normal number.
      * ``"+Infinity"``, indicating that the operand is positive infinity.
      * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
      * ``"sNaN"``, indicating that the operand is a signaling NaN.
744

745
   .. method:: quantize(exp, rounding=None, context=None, watchexp=True)
746

747 748
      Return a value equal to the first operand after rounding and having the
      exponent of the second operand.
749

750 751
      >>> Decimal('1.41421356').quantize(Decimal('1.000'))
      Decimal('1.414')
752

753 754 755 756 757
      Unlike other operations, if the length of the coefficient after the
      quantize operation would be greater than precision, then an
      :const:`InvalidOperation` is signaled. This guarantees that, unless there
      is an error condition, the quantized exponent is always equal to that of
      the right-hand operand.
758

759 760
      Also unlike other operations, quantize never signals Underflow, even if
      the result is subnormal and inexact.
761

762 763 764 765 766
      If the exponent of the second operand is larger than that of the first
      then rounding may be necessary.  In this case, the rounding mode is
      determined by the ``rounding`` argument if given, else by the given
      ``context`` argument; if neither argument is given the rounding mode of
      the current thread's context is used.
767

768 769 770
      If *watchexp* is set (default), then an error is returned whenever the
      resulting exponent is greater than :attr:`Emax` or less than
      :attr:`Etiny`.
771

772 773 774 775 776
      .. deprecated:: 3.3
         *watchexp* is an implementation detail from the pure Python version
         and is not present in the C version. It will be removed in version
         3.4, where it defaults to ``True``.

777
   .. method:: radix()
778

779 780 781
      Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
      class does all its arithmetic.  Included for compatibility with the
      specification.
782

783
   .. method:: remainder_near(other, context=None)
784

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
      Return the remainder from dividing *self* by *other*.  This differs from
      ``self % other`` in that the sign of the remainder is chosen so as to
      minimize its absolute value.  More precisely, the return value is
      ``self - n * other`` where ``n`` is the integer nearest to the exact
      value of ``self / other``, and if two integers are equally near then the
      even one is chosen.

      If the result is zero then its sign will be the sign of *self*.

      >>> Decimal(18).remainder_near(Decimal(10))
      Decimal('-2')
      >>> Decimal(25).remainder_near(Decimal(10))
      Decimal('5')
      >>> Decimal(35).remainder_near(Decimal(10))
      Decimal('-5')
800

801
   .. method:: rotate(other, context=None)
802

803 804 805 806 807 808 809 810
      Return the result of rotating the digits of the first operand by an amount
      specified by the second operand.  The second operand must be an integer in
      the range -precision through precision.  The absolute value of the second
      operand gives the number of places to rotate.  If the second operand is
      positive then rotation is to the left; otherwise rotation is to the right.
      The coefficient of the first operand is padded on the left with zeros to
      length precision if necessary.  The sign and exponent of the first operand
      are unchanged.
811

812
   .. method:: same_quantum(other, context=None)
813

814 815
      Test whether self and other have the same exponent or whether both are
      :const:`NaN`.
816

817 818 819 820 821
      This operation is unaffected by context and is quiet: no flags are changed
      and no rounding is performed.  As an exception, the C version may raise
      InvalidOperation if the second operand cannot be converted exactly.

   .. method:: scaleb(other, context=None)
822

823 824 825
      Return the first operand with exponent adjusted by the second.
      Equivalently, return the first operand multiplied by ``10**other``.  The
      second operand must be an integer.
826

827
   .. method:: shift(other, context=None)
828

829 830 831 832 833 834 835
      Return the result of shifting the digits of the first operand by an amount
      specified by the second operand.  The second operand must be an integer in
      the range -precision through precision.  The absolute value of the second
      operand gives the number of places to shift.  If the second operand is
      positive then the shift is to the left; otherwise the shift is to the
      right.  Digits shifted into the coefficient are zeros.  The sign and
      exponent of the first operand are unchanged.
836

837
   .. method:: sqrt(context=None)
838

839
      Return the square root of the argument to full precision.
840 841


842
   .. method:: to_eng_string(context=None)
843

844
      Convert to an engineering-type string.
845

846 847 848
      Engineering notation has an exponent which is a multiple of 3, so there
      are up to 3 digits left of the decimal place.  For example, converts
      ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
849

850
   .. method:: to_integral(rounding=None, context=None)
851

852 853
      Identical to the :meth:`to_integral_value` method.  The ``to_integral``
      name has been kept for compatibility with older versions.
854

855
   .. method:: to_integral_exact(rounding=None, context=None)
856

857 858 859 860 861
      Round to the nearest integer, signaling :const:`Inexact` or
      :const:`Rounded` as appropriate if rounding occurs.  The rounding mode is
      determined by the ``rounding`` parameter if given, else by the given
      ``context``.  If neither parameter is given then the rounding mode of the
      current context is used.
862

863
   .. method:: to_integral_value(rounding=None, context=None)
864

865 866 867
      Round to the nearest integer without signaling :const:`Inexact` or
      :const:`Rounded`.  If given, applies *rounding*; otherwise, uses the
      rounding method in either the supplied *context* or the current context.
868

869 870 871 872 873 874 875 876 877 878 879 880

.. _logical_operands_label:

Logical operands
^^^^^^^^^^^^^^^^

The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
and :meth:`logical_xor` methods expect their arguments to be *logical
operands*.  A *logical operand* is a :class:`Decimal` instance whose
exponent and sign are both zero, and whose digits are all either
:const:`0` or :const:`1`.

881
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905


.. _decimal-context:

Context objects
---------------

Contexts are environments for arithmetic operations.  They govern precision, set
rules for rounding, determine which signals are treated as exceptions, and limit
the range for exponents.

Each thread has its own current context which is accessed or changed using the
:func:`getcontext` and :func:`setcontext` functions:


.. function:: getcontext()

   Return the current context for the active thread.


.. function:: setcontext(c)

   Set the current context for the active thread to *c*.

906 907
You can also use the :keyword:`with` statement and the :func:`localcontext`
function to temporarily change the active context.
908

909
.. function:: localcontext(ctx=None)
910 911

   Return a context manager that will set the current context for the active thread
912
   to a copy of *ctx* on entry to the with-statement and restore the previous context
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
   when exiting the with-statement. If no context is specified, a copy of the
   current context is used.

   For example, the following code sets the current decimal precision to 42 places,
   performs a calculation, and then automatically restores the previous context::

      from decimal import localcontext

      with localcontext() as ctx:
          ctx.prec = 42   # Perform a high precision calculation
          s = calculate_something()
      s = +s  # Round the final result back to the default precision

New contexts can also be created using the :class:`Context` constructor
described below. In addition, the module provides three pre-made contexts:


.. class:: BasicContext

   This is a standard context defined by the General Decimal Arithmetic
   Specification.  Precision is set to nine.  Rounding is set to
   :const:`ROUND_HALF_UP`.  All flags are cleared.  All traps are enabled (treated
   as exceptions) except :const:`Inexact`, :const:`Rounded`, and
   :const:`Subnormal`.

   Because many of the traps are enabled, this context is useful for debugging.


.. class:: ExtendedContext

   This is a standard context defined by the General Decimal Arithmetic
   Specification.  Precision is set to nine.  Rounding is set to
   :const:`ROUND_HALF_EVEN`.  All flags are cleared.  No traps are enabled (so that
   exceptions are not raised during computations).

Christian Heimes's avatar
Christian Heimes committed
948
   Because the traps are disabled, this context is useful for applications that
949 950 951 952 953 954 955 956 957
   prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
   raising exceptions.  This allows an application to complete a run in the
   presence of conditions that would otherwise halt the program.


.. class:: DefaultContext

   This context is used by the :class:`Context` constructor as a prototype for new
   contexts.  Changing a field (such a precision) has the effect of changing the
958
   default for new contexts created by the :class:`Context` constructor.
959 960 961 962 963 964 965 966 967

   This context is most useful in multi-threaded environments.  Changing one of the
   fields before threads are started has the effect of setting system-wide
   defaults.  Changing the fields after threads have started is not recommended as
   it would require thread synchronization to prevent race conditions.

   In single threaded environments, it is preferable to not use this context at
   all.  Instead, simply create contexts explicitly as described below.

968 969 970 971
   The default values are :attr:`prec`\ =\ :const:`28`,
   :attr:`rounding`\ =\ :const:`ROUND_HALF_EVEN`,
   and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and
   :class:`DivisionByZero`.
972 973 974 975 976

In addition to the three supplied contexts, new contexts can be created with the
:class:`Context` constructor.


977
.. class:: Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)
978 979 980 981 982

   Creates a new context.  If a field is not specified or is :const:`None`, the
   default values are copied from the :const:`DefaultContext`.  If the *flags*
   field is not specified or is :const:`None`, all flags are cleared.

983 984
   *prec* is an integer in the range [:const:`1`, :const:`MAX_PREC`] that sets
   the precision for arithmetic operations in the context.
985

986 987
   The *rounding* option is one of the constants listed in the section
   `Rounding Modes`_.
988 989 990 991 992

   The *traps* and *flags* fields list any signals to be set. Generally, new
   contexts should only set traps and leave the flags clear.

   The *Emin* and *Emax* fields are integers specifying the outer limits allowable
993 994
   for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, :const:`0`],
   *Emax* in the range [:const:`0`, :const:`MAX_EMAX`].
995 996 997 998 999

   The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
   :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
   lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
   The *clamp* field is either :const:`0` (the default) or :const:`1`.
   If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
   instance representable in this context is strictly limited to the
   range ``Emin - prec + 1 <= e <= Emax - prec + 1``.  If *clamp* is
   :const:`0` then a weaker condition holds: the adjusted exponent of
   the :class:`Decimal` instance is at most ``Emax``.  When *clamp* is
   :const:`1`, a large normal number will, where possible, have its
   exponent reduced and a corresponding number of zeros added to its
   coefficient, in order to fit the exponent constraints; this
   preserves the value of the number but loses information about
   significant trailing zeros.  For example::

      >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
      Decimal('1.23000E+999')

   A *clamp* value of :const:`1` allows compatibility with the
   fixed-width decimal interchange formats specified in IEEE 754.
1017

1018 1019 1020 1021
   The :class:`Context` class defines several general purpose methods as well as
   a large number of methods for doing arithmetic directly in a given context.
   In addition, for each of the :class:`Decimal` methods described above (with
   the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
1022 1023 1024
   a corresponding :class:`Context` method.  For example, for a :class:`Context`
   instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
   equivalent to ``x.exp(context=C)``.  Each :class:`Context` method accepts a
1025
   Python integer (an instance of :class:`int`) anywhere that a
1026
   Decimal instance is accepted.
1027 1028


1029
   .. method:: clear_flags()
1030

1031
      Resets all of the flags to :const:`0`.
1032

1033 1034 1035 1036 1037 1038
   .. method:: clear_traps()

      Resets all of the traps to :const:`0`.

      .. versionadded:: 3.3

1039
   .. method:: copy()
1040

1041
      Return a duplicate of the context.
1042

1043
   .. method:: copy_decimal(num)
1044

1045
      Return a copy of the Decimal instance num.
1046

1047
   .. method:: create_decimal(num)
1048

1049 1050 1051
      Creates a new Decimal instance from *num* but using *self* as
      context. Unlike the :class:`Decimal` constructor, the context precision,
      rounding method, flags, and traps are applied to the conversion.
Christian Heimes's avatar
Christian Heimes committed
1052

1053 1054 1055 1056 1057
      This is useful because constants are often given to a greater precision
      than is needed by the application.  Another benefit is that rounding
      immediately eliminates unintended effects from digits beyond the current
      precision. In the following example, using unrounded inputs means that
      adding zero to a sum can change the result:
1058

1059
      .. doctest:: newcontext
1060

1061 1062 1063 1064 1065
         >>> getcontext().prec = 3
         >>> Decimal('3.4445') + Decimal('1.0023')
         Decimal('4.45')
         >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
         Decimal('4.44')
1066

1067 1068 1069
      This method implements the to-number operation of the IBM specification.
      If the argument is a string, no leading or trailing whitespace is
      permitted.
1070

1071
   .. method:: create_decimal_from_float(f)
1072 1073

      Creates a new Decimal instance from a float *f* but rounding using *self*
1074
      as the context.  Unlike the :meth:`Decimal.from_float` class method,
1075 1076 1077 1078 1079
      the context precision, rounding method, flags, and traps are applied to
      the conversion.

      .. doctest::

1080 1081 1082 1083 1084 1085 1086 1087
         >>> context = Context(prec=5, rounding=ROUND_DOWN)
         >>> context.create_decimal_from_float(math.pi)
         Decimal('3.1415')
         >>> context = Context(prec=5, traps=[Inexact])
         >>> context.create_decimal_from_float(math.pi)
         Traceback (most recent call last):
             ...
         decimal.Inexact: None
1088

1089
      .. versionadded:: 3.1
1090

1091
   .. method:: Etiny()
1092

1093 1094 1095
      Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
      value for subnormal results.  When underflow occurs, the exponent is set
      to :const:`Etiny`.
1096

1097
   .. method:: Etop()
1098

1099
      Returns a value equal to ``Emax - prec + 1``.
1100

1101 1102 1103 1104 1105 1106
   The usual approach to working with decimals is to create :class:`Decimal`
   instances and then apply arithmetic operations which take place within the
   current context for the active thread.  An alternative approach is to use
   context methods for calculating within a specific context.  The methods are
   similar to those for the :class:`Decimal` class and are only briefly
   recounted here.
1107 1108


1109
   .. method:: abs(x)
1110

1111
      Returns the absolute value of *x*.
1112 1113


1114
   .. method:: add(x, y)
1115

1116
      Return the sum of *x* and *y*.
1117 1118


1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
   .. method:: canonical(x)

      Returns the same Decimal object *x*.


   .. method:: compare(x, y)

      Compares *x* and *y* numerically.


   .. method:: compare_signal(x, y)

      Compares the values of the two operands numerically.


   .. method:: compare_total(x, y)

      Compares two operands using their abstract representation.


   .. method:: compare_total_mag(x, y)

      Compares two operands using their abstract representation, ignoring sign.


   .. method:: copy_abs(x)

      Returns a copy of *x* with the sign set to 0.


   .. method:: copy_negate(x)

      Returns a copy of *x* with the sign inverted.


   .. method:: copy_sign(x, y)

      Copies the sign from *y* to *x*.


1159
   .. method:: divide(x, y)
1160

1161
      Return *x* divided by *y*.
1162 1163


1164
   .. method:: divide_int(x, y)
1165

1166
      Return *x* divided by *y*, truncated to an integer.
1167 1168


1169
   .. method:: divmod(x, y)
1170

1171
      Divides two numbers and returns the integer part of the result.
1172 1173


1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
   .. method:: exp(x)

      Returns `e ** x`.


   .. method:: fma(x, y, z)

      Returns *x* multiplied by *y*, plus *z*.


   .. method:: is_canonical(x)

1186
      Returns ``True`` if *x* is canonical; otherwise returns ``False``.
1187 1188 1189 1190


   .. method:: is_finite(x)

1191
      Returns ``True`` if *x* is finite; otherwise returns ``False``.
1192 1193 1194 1195


   .. method:: is_infinite(x)

1196
      Returns ``True`` if *x* is infinite; otherwise returns ``False``.
1197 1198 1199 1200


   .. method:: is_nan(x)

1201
      Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.
1202 1203 1204 1205


   .. method:: is_normal(x)

1206
      Returns ``True`` if *x* is a normal number; otherwise returns ``False``.
1207 1208 1209 1210


   .. method:: is_qnan(x)

1211
      Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.
1212 1213 1214 1215


   .. method:: is_signed(x)

1216
      Returns ``True`` if *x* is negative; otherwise returns ``False``.
1217 1218 1219 1220


   .. method:: is_snan(x)

1221
      Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.
1222 1223 1224 1225


   .. method:: is_subnormal(x)

1226
      Returns ``True`` if *x* is subnormal; otherwise returns ``False``.
1227 1228 1229 1230


   .. method:: is_zero(x)

1231
      Returns ``True`` if *x* is a zero; otherwise returns ``False``.
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250


   .. method:: ln(x)

      Returns the natural (base e) logarithm of *x*.


   .. method:: log10(x)

      Returns the base 10 logarithm of *x*.


   .. method:: logb(x)

       Returns the exponent of the magnitude of the operand's MSD.


   .. method:: logical_and(x, y)

1251
      Applies the logical operation *and* between each operand's digits.
1252 1253 1254 1255 1256 1257 1258 1259 1260


   .. method:: logical_invert(x)

      Invert all the digits in *x*.


   .. method:: logical_or(x, y)

1261
      Applies the logical operation *or* between each operand's digits.
1262 1263 1264 1265


   .. method:: logical_xor(x, y)

1266
      Applies the logical operation *xor* between each operand's digits.
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288


   .. method:: max(x, y)

      Compares two values numerically and returns the maximum.


   .. method:: max_mag(x, y)

      Compares the values numerically with their sign ignored.


   .. method:: min(x, y)

      Compares two values numerically and returns the minimum.


   .. method:: min_mag(x, y)

      Compares the values numerically with their sign ignored.


1289
   .. method:: minus(x)
1290

1291
      Minus corresponds to the unary prefix minus operator in Python.
1292 1293


1294
   .. method:: multiply(x, y)
1295

1296
      Return the product of *x* and *y*.
1297 1298


1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
   .. method:: next_minus(x)

      Returns the largest representable number smaller than *x*.


   .. method:: next_plus(x)

      Returns the smallest representable number larger than *x*.


   .. method:: next_toward(x, y)

      Returns the number closest to *x*, in direction towards *y*.


   .. method:: normalize(x)

      Reduces *x* to its simplest form.


   .. method:: number_class(x)

      Returns an indication of the class of *x*.


1324
   .. method:: plus(x)
1325

1326 1327 1328
      Plus corresponds to the unary prefix plus operator in Python.  This
      operation applies the context precision and rounding, so it is *not* an
      identity operation.
1329 1330


1331
   .. method:: power(x, y, modulo=None)
1332

1333
      Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
1334

1335 1336 1337
      With two arguments, compute ``x**y``.  If ``x`` is negative then ``y``
      must be integral.  The result will be inexact unless ``y`` is integral and
      the result is finite and can be expressed exactly in 'precision' digits.
1338 1339 1340 1341 1342 1343 1344
      The rounding mode of the context is used. Results are always correctly-rounded
      in the Python version.

      .. versionchanged:: 3.3
         The C module computes :meth:`power` in terms of the correctly-rounded
         :meth:`exp` and :meth:`ln` functions. The result is well-defined but
         only "almost always correctly-rounded".
1345

1346 1347
      With three arguments, compute ``(x**y) % modulo``.  For the three argument
      form, the following restrictions on the arguments hold:
1348

1349 1350 1351 1352
         - all three arguments must be integral
         - ``y`` must be nonnegative
         - at least one of ``x`` or ``y`` must be nonzero
         - ``modulo`` must be nonzero and have at most 'precision' digits
1353

1354 1355 1356 1357 1358 1359
      The value resulting from ``Context.power(x, y, modulo)`` is
      equal to the value that would be obtained by computing ``(x**y)
      % modulo`` with unbounded precision, but is computed more
      efficiently.  The exponent of the result is zero, regardless of
      the exponents of ``x``, ``y`` and ``modulo``.  The result is
      always exact.
1360

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371

   .. method:: quantize(x, y)

      Returns a value equal to *x* (rounded), having the exponent of *y*.


   .. method:: radix()

      Just returns 10, as this is Decimal, :)


1372
   .. method:: remainder(x, y)
1373

1374
      Returns the remainder from integer division.
1375

1376 1377
      The sign of the result, if non-zero, is the same as that of the original
      dividend.
1378

Benjamin Peterson's avatar
Benjamin Peterson committed
1379

1380 1381
   .. method:: remainder_near(x, y)

1382 1383
      Returns ``x - y * n``, where *n* is the integer nearest the exact value
      of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
1384 1385 1386 1387 1388 1389 1390 1391 1392


   .. method:: rotate(x, y)

      Returns a rotated copy of *x*, *y* times.


   .. method:: same_quantum(x, y)

1393
      Returns ``True`` if the two operands have the same exponent.
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410


   .. method:: scaleb (x, y)

      Returns the first operand after adding the second value its exp.


   .. method:: shift(x, y)

      Returns a shifted copy of *x*, *y* times.


   .. method:: sqrt(x)

      Square root of a non-negative number to context precision.


1411
   .. method:: subtract(x, y)
1412

1413
      Return the difference between *x* and *y*.
1414

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

   .. method:: to_eng_string(x)

      Converts a number to a string, using scientific notation.


   .. method:: to_integral_exact(x)

      Rounds to an integer.


1426
   .. method:: to_sci_string(x)
1427

1428
      Converts a number to a string using scientific notation.
1429

1430
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1431

1432 1433 1434 1435 1436 1437 1438 1439
.. _decimal-rounding-modes:

Constants
---------

The constants in this section are only relevant for the C module. They
are also included in the pure Python version for compatibility.

1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
+---------------------+---------------------+-------------------------------+
|                     |       32-bit        |            64-bit             |
+=====================+=====================+===============================+
| .. data:: MAX_PREC  | :const:`425000000`  | :const:`999999999999999999`   |
+---------------------+---------------------+-------------------------------+
| .. data:: MAX_EMAX  | :const:`425000000`  | :const:`999999999999999999`   |
+---------------------+---------------------+-------------------------------+
| .. data:: MIN_EMIN  | :const:`-425000000` | :const:`-999999999999999999`  |
+---------------------+---------------------+-------------------------------+
| .. data:: MIN_ETINY | :const:`-849999999` | :const:`-1999999999999999997` |
+---------------------+---------------------+-------------------------------+

1452 1453 1454

.. data:: HAVE_THREADS

1455
   The default value is ``True``. If Python is compiled without threads, the
1456
   C version automatically disables the expensive thread local context
1457
   machinery. In this case, the value is ``False``.
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494

Rounding modes
--------------

.. data:: ROUND_CEILING

   Round towards :const:`Infinity`.

.. data:: ROUND_DOWN

   Round towards zero.

.. data:: ROUND_FLOOR

   Round towards :const:`-Infinity`.

.. data:: ROUND_HALF_DOWN

   Round to nearest with ties going towards zero.

.. data:: ROUND_HALF_EVEN

   Round to nearest with ties going to nearest even integer.

.. data:: ROUND_HALF_UP

   Round to nearest with ties going away from zero.

.. data:: ROUND_UP

   Round away from zero.

.. data:: ROUND_05UP

   Round away from zero if last digit after rounding towards zero would have
   been 0 or 5; otherwise round towards zero.

1495 1496 1497 1498 1499 1500 1501 1502 1503

.. _decimal-signals:

Signals
-------

Signals represent conditions that arise during computation. Each corresponds to
one context flag and one context trap enabler.

1504
The context flag is set whenever the condition is encountered. After the
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
computation, flags may be checked for informational purposes (for instance, to
determine whether a computation was exact). After checking the flags, be sure to
clear all flags before starting the next computation.

If the context's trap enabler is set for the signal, then the condition causes a
Python exception to be raised.  For example, if the :class:`DivisionByZero` trap
is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
condition.


.. class:: Clamped

   Altered an exponent to fit representation constraints.

   Typically, clamping occurs when an exponent falls outside the context's
   :attr:`Emin` and :attr:`Emax` limits.  If possible, the exponent is reduced to
1521
   fit by adding zeros to the coefficient.
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561


.. class:: DecimalException

   Base class for other signals and a subclass of :exc:`ArithmeticError`.


.. class:: DivisionByZero

   Signals the division of a non-infinite number by zero.

   Can occur with division, modulo division, or when raising a number to a negative
   power.  If this signal is not trapped, returns :const:`Infinity` or
   :const:`-Infinity` with the sign determined by the inputs to the calculation.


.. class:: Inexact

   Indicates that rounding occurred and the result is not exact.

   Signals when non-zero digits were discarded during rounding. The rounded result
   is returned.  The signal flag or trap is used to detect when results are
   inexact.


.. class:: InvalidOperation

   An invalid operation was performed.

   Indicates that an operation was requested that does not make sense. If not
   trapped, returns :const:`NaN`.  Possible causes include::

      Infinity - Infinity
      0 * Infinity
      Infinity / Infinity
      x % 0
      Infinity % x
      sqrt(-x) and x > 0
      0 ** 0
      x ** (non-integer)
1562
      x ** Infinity
1563 1564 1565 1566 1567 1568


.. class:: Overflow

   Numerical overflow.

1569 1570 1571 1572 1573
   Indicates the exponent is larger than :attr:`Emax` after rounding has
   occurred.  If not trapped, the result depends on the rounding mode, either
   pulling inward to the largest representable finite number or rounding outward
   to :const:`Infinity`.  In either case, :class:`Inexact` and :class:`Rounded`
   are also signaled.
1574 1575 1576 1577 1578 1579


.. class:: Rounded

   Rounding occurred though possibly no information was lost.

1580 1581 1582 1583
   Signaled whenever rounding discards digits; even if those digits are zero
   (such as rounding :const:`5.00` to :const:`5.0`).  If not trapped, returns
   the result unchanged.  This signal is used to detect loss of significant
   digits.
1584 1585 1586 1587 1588 1589


.. class:: Subnormal

   Exponent was lower than :attr:`Emin` prior to rounding.

1590 1591
   Occurs when an operation result is subnormal (the exponent is too small). If
   not trapped, returns the result unchanged.
1592 1593 1594 1595 1596 1597 1598 1599 1600


.. class:: Underflow

   Numerical underflow with result rounded to zero.

   Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
   and :class:`Subnormal` are also signaled.

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

.. class:: FloatOperation

    Enable stricter semantics for mixing floats and Decimals.

    If the signal is not trapped (default), mixing floats and Decimals is
    permitted in the :class:`~decimal.Decimal` constructor,
    :meth:`~decimal.Context.create_decimal` and all comparison operators.
    Both conversion and comparisons are exact. Any occurrence of a mixed
    operation is silently recorded by setting :exc:`FloatOperation` in the
    context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
    or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.

    Otherwise (the signal is trapped), only equality comparisons and explicit
    conversions are silent. All other mixed operations raise :exc:`FloatOperation`.


1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
The following table summarizes the hierarchy of signals::

   exceptions.ArithmeticError(exceptions.Exception)
       DecimalException
           Clamped
           DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
           Inexact
               Overflow(Inexact, Rounded)
               Underflow(Inexact, Rounded, Subnormal)
           InvalidOperation
           Rounded
           Subnormal
1630
           FloatOperation(DecimalException, exceptions.TypeError)
1631

1632
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1633 1634


1635

1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
.. _decimal-notes:

Floating Point Notes
--------------------


Mitigating round-off error with increased precision
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The use of decimal floating point eliminates decimal representation error
(making it possible to represent :const:`0.1` exactly); however, some operations
can still incur round-off error when non-zero digits exceed the fixed precision.

The effects of round-off error can be amplified by the addition or subtraction
of nearly offsetting quantities resulting in loss of significance.  Knuth
provides two instructive examples where rounded floating point arithmetic with
insufficient precision causes the breakdown of the associative and distributive
Christian Heimes's avatar
Christian Heimes committed
1653 1654 1655
properties of addition:

.. doctest:: newcontext
1656 1657 1658 1659 1660 1661 1662

   # Examples from Seminumerical Algorithms, Section 4.2.2.
   >>> from decimal import Decimal, getcontext
   >>> getcontext().prec = 8

   >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
   >>> (u + v) + w
Christian Heimes's avatar
Christian Heimes committed
1663
   Decimal('9.5111111')
1664
   >>> u + (v + w)
Christian Heimes's avatar
Christian Heimes committed
1665
   Decimal('10')
1666 1667 1668

   >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
   >>> (u*v) + (u*w)
Christian Heimes's avatar
Christian Heimes committed
1669
   Decimal('0.01')
1670
   >>> u * (v+w)
Christian Heimes's avatar
Christian Heimes committed
1671
   Decimal('0.0060000')
1672 1673

The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimes's avatar
Christian Heimes committed
1674 1675 1676
expanding the precision sufficiently to avoid loss of significance:

.. doctest:: newcontext
1677 1678 1679 1680

   >>> getcontext().prec = 20
   >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
   >>> (u + v) + w
Christian Heimes's avatar
Christian Heimes committed
1681
   Decimal('9.51111111')
1682
   >>> u + (v + w)
Christian Heimes's avatar
Christian Heimes committed
1683
   Decimal('9.51111111')
1684
   >>>
1685 1686
   >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
   >>> (u*v) + (u*w)
Christian Heimes's avatar
Christian Heimes committed
1687
   Decimal('0.0060000')
1688
   >>> u * (v+w)
Christian Heimes's avatar
Christian Heimes committed
1689
   Decimal('0.0060000')
1690 1691 1692 1693 1694 1695 1696


Special values
^^^^^^^^^^^^^^

The number system for the :mod:`decimal` module provides special values
including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
1697
and two zeros, :const:`+0` and :const:`-0`.
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

Infinities can be constructed directly with:  ``Decimal('Infinity')``. Also,
they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
not trapped.  Likewise, when the :exc:`Overflow` signal is not trapped, infinity
can result from rounding beyond the limits of the largest representable number.

The infinities are signed (affine) and can be used in arithmetic operations
where they get treated as very large, indeterminate numbers.  For instance,
adding a constant to infinity gives another infinite result.

Some operations are indeterminate and return :const:`NaN`, or if the
:exc:`InvalidOperation` signal is trapped, raise an exception.  For example,
``0/0`` returns :const:`NaN` which means "not a number".  This variety of
:const:`NaN` is quiet and, once created, will flow through other computations
always resulting in another :const:`NaN`.  This behavior can be useful for a
series of computations that occasionally have missing inputs --- it allows the
calculation to proceed while flagging specific results as invalid.

A variant is :const:`sNaN` which signals rather than remaining quiet after every
operation.  This is a useful return value when an invalid result needs to
interrupt a calculation for special handling.

Christian Heimes's avatar
Christian Heimes committed
1720 1721 1722 1723 1724 1725 1726
The behavior of Python's comparison operators can be a little surprising where a
:const:`NaN` is involved.  A test for equality where one of the operands is a
quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
:const:`True`.  An attempt to compare two Decimals using any of the ``<``,
``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes's avatar
Christian Heimes committed
1727
not trapped.  Note that the General Decimal Arithmetic specification does not
Christian Heimes's avatar
Christian Heimes committed
1728 1729 1730 1731 1732
specify the behavior of direct comparisons; these rules for comparisons
involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
section 5.7).  To ensure strict standards-compliance, use the :meth:`compare`
and :meth:`compare-signal` methods instead.

1733 1734 1735 1736 1737 1738 1739 1740 1741
The signed zeros can result from calculations that underflow. They keep the sign
that would have resulted if the calculation had been carried out to greater
precision.  Since their magnitude is zero, both positive and negative zeros are
treated as equal and their sign is informational.

In addition to the two signed zeros which are distinct yet equal, there are
various representations of zero with differing precisions yet equivalent in
value.  This takes a bit of getting used to.  For an eye accustomed to
normalized floating point representations, it is not immediately obvious that
Christian Heimes's avatar
Christian Heimes committed
1742
the following calculation returns a value equal to zero:
1743 1744

   >>> 1 / Decimal('Infinity')
1745
   Decimal('0E-1000026')
1746

1747
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1748 1749 1750 1751 1752 1753 1754 1755 1756


.. _decimal-threads:

Working with threads
--------------------

The :func:`getcontext` function accesses a different :class:`Context` object for
each thread.  Having separate thread contexts means that threads may make
1757
changes (such as ``getcontext().prec=10``) without interfering with other threads.
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784

Likewise, the :func:`setcontext` function automatically assigns its target to
the current thread.

If :func:`setcontext` has not been called before :func:`getcontext`, then
:func:`getcontext` will automatically create a new context for use in the
current thread.

The new context is copied from a prototype context called *DefaultContext*. To
control the defaults so that each thread will use the same values throughout the
application, directly modify the *DefaultContext* object. This should be done
*before* any threads are started so that there won't be a race condition between
threads calling :func:`getcontext`. For example::

   # Set applicationwide defaults for all threads about to be launched
   DefaultContext.prec = 12
   DefaultContext.rounding = ROUND_DOWN
   DefaultContext.traps = ExtendedContext.traps.copy()
   DefaultContext.traps[InvalidOperation] = 1
   setcontext(DefaultContext)

   # Afterwards, the threads can be started
   t1.start()
   t2.start()
   t3.start()
    . . .

1785
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818


.. _decimal-recipes:

Recipes
-------

Here are a few recipes that serve as utility functions and that demonstrate ways
to work with the :class:`Decimal` class::

   def moneyfmt(value, places=2, curr='', sep=',', dp='.',
                pos='', neg='-', trailneg=''):
       """Convert Decimal to a money formatted string.

       places:  required number of places after the decimal point
       curr:    optional currency symbol before the sign (may be blank)
       sep:     optional grouping separator (comma, period, space, or blank)
       dp:      decimal point indicator (comma or period)
                only specify as blank when places is zero
       pos:     optional sign for positive numbers: '+', space or blank
       neg:     optional sign for negative numbers: '-', '(', space or blank
       trailneg:optional trailing minus indicator:  '-', ')', space or blank

       >>> d = Decimal('-1234567.8901')
       >>> moneyfmt(d, curr='$')
       '-$1,234,567.89'
       >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
       '1.234.568-'
       >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
       '($1,234,567.89)'
       >>> moneyfmt(Decimal(123456789), sep=' ')
       '123 456 789.00'
       >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimes's avatar
Christian Heimes committed
1819
       '<0.02>'
1820 1821

       """
Christian Heimes's avatar
Christian Heimes committed
1822
       q = Decimal(10) ** -places      # 2 places --> '0.01'
1823
       sign, digits, exp = value.quantize(q).as_tuple()
1824
       result = []
1825
       digits = list(map(str, digits))
1826 1827 1828 1829
       build, next = result.append, digits.pop
       if sign:
           build(trailneg)
       for i in range(places):
Christian Heimes's avatar
Christian Heimes committed
1830
           build(next() if digits else '0')
1831 1832
       if places:
           build(dp)
Christian Heimes's avatar
Christian Heimes committed
1833 1834
       if not digits:
           build('0')
1835 1836 1837 1838 1839 1840 1841 1842
       i = 0
       while digits:
           build(next())
           i += 1
           if i == 3 and digits:
               i = 0
               build(sep)
       build(curr)
Christian Heimes's avatar
Christian Heimes committed
1843 1844
       build(neg if sign else pos)
       return ''.join(reversed(result))
1845 1846 1847 1848

   def pi():
       """Compute Pi to the current precision.

1849
       >>> print(pi())
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
       3.141592653589793238462643383

       """
       getcontext().prec += 2  # extra digits for intermediate steps
       three = Decimal(3)      # substitute "three=3.0" for regular floats
       lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
       while s != lasts:
           lasts = s
           n, na = n+na, na+8
           d, da = d+da, da+32
           t = (t * n) / d
           s += t
       getcontext().prec -= 2
       return +s               # unary plus applies the new precision

   def exp(x):
       """Return e raised to the power of x.  Result type matches input type.

1868
       >>> print(exp(Decimal(1)))
1869
       2.718281828459045235360287471
1870
       >>> print(exp(Decimal(2)))
1871
       7.389056098930650227230427461
1872
       >>> print(exp(2.0))
1873
       7.38905609893
1874
       >>> print(exp(2+0j))
1875 1876 1877 1878 1879 1880
       (7.38905609893+0j)

       """
       getcontext().prec += 2
       i, lasts, s, fact, num = 0, 0, 1, 1, 1
       while s != lasts:
1881
           lasts = s
1882 1883
           i += 1
           fact *= i
1884 1885 1886
           num *= x
           s += num / fact
       getcontext().prec -= 2
1887 1888 1889 1890 1891
       return +s

   def cos(x):
       """Return the cosine of x as measured in radians.

Mark Dickinson's avatar
Mark Dickinson committed
1892
       The Taylor series approximation works best for a small value of x.
1893 1894
       For larger values, first compute x = x % (2 * pi).

1895
       >>> print(cos(Decimal('0.5')))
1896
       0.8775825618903727161162815826
1897
       >>> print(cos(0.5))
1898
       0.87758256189
1899
       >>> print(cos(0.5+0j))
1900 1901 1902 1903 1904 1905
       (0.87758256189+0j)

       """
       getcontext().prec += 2
       i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
       while s != lasts:
1906
           lasts = s
1907 1908 1909 1910
           i += 2
           fact *= i * (i-1)
           num *= x * x
           sign *= -1
1911 1912
           s += num / fact * sign
       getcontext().prec -= 2
1913 1914 1915 1916 1917
       return +s

   def sin(x):
       """Return the sine of x as measured in radians.

Mark Dickinson's avatar
Mark Dickinson committed
1918
       The Taylor series approximation works best for a small value of x.
1919 1920
       For larger values, first compute x = x % (2 * pi).

1921
       >>> print(sin(Decimal('0.5')))
1922
       0.4794255386042030002732879352
1923
       >>> print(sin(0.5))
1924
       0.479425538604
1925
       >>> print(sin(0.5+0j))
1926 1927 1928 1929 1930 1931
       (0.479425538604+0j)

       """
       getcontext().prec += 2
       i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
       while s != lasts:
1932
           lasts = s
1933 1934 1935 1936
           i += 2
           fact *= i * (i-1)
           num *= x * x
           sign *= -1
1937 1938
           s += num / fact * sign
       getcontext().prec -= 2
1939 1940 1941
       return +s


1942
.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952


.. _decimal-faq:

Decimal FAQ
-----------

Q. It is cumbersome to type ``decimal.Decimal('1234.5')``.  Is there a way to
minimize typing when using the interactive interpreter?

Christian Heimes's avatar
Christian Heimes committed
1953
A. Some users abbreviate the constructor to just a single letter:
1954 1955 1956

   >>> D = decimal.Decimal
   >>> D('1.23') + D('3.45')
Christian Heimes's avatar
Christian Heimes committed
1957
   Decimal('4.68')
1958 1959 1960 1961 1962 1963

Q. In a fixed-point application with two decimal places, some inputs have many
places and need to be rounded.  Others are not supposed to have excess digits
and need to be validated.  What methods should be used?

A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimes's avatar
Christian Heimes committed
1964
the :const:`Inexact` trap is set, it is also useful for validation:
1965 1966 1967 1968

   >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')

   >>> # Round to two places
Christian Heimes's avatar
Christian Heimes committed
1969 1970
   >>> Decimal('3.214').quantize(TWOPLACES)
   Decimal('3.21')
1971

1972
   >>> # Validate that a number does not exceed two places
Christian Heimes's avatar
Christian Heimes committed
1973 1974
   >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
   Decimal('3.21')
1975

Christian Heimes's avatar
Christian Heimes committed
1976
   >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1977 1978
   Traceback (most recent call last):
      ...
Benjamin Peterson's avatar
Benjamin Peterson committed
1979
   Inexact: None
1980 1981 1982 1983

Q. Once I have valid two place inputs, how do I maintain that invariant
throughout an application?

Christian Heimes's avatar
Christian Heimes committed
1984 1985 1986
A. Some operations like addition, subtraction, and multiplication by an integer
will automatically preserve fixed point.  Others operations, like division and
non-integer multiplication, will change the number of decimal places and need to
Christian Heimes's avatar
Christian Heimes committed
1987
be followed-up with a :meth:`quantize` step:
Christian Heimes's avatar
Christian Heimes committed
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002

    >>> a = Decimal('102.72')           # Initial fixed-point values
    >>> b = Decimal('3.17')
    >>> a + b                           # Addition preserves fixed-point
    Decimal('105.89')
    >>> a - b
    Decimal('99.55')
    >>> a * 42                          # So does integer multiplication
    Decimal('4314.24')
    >>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
    Decimal('325.62')
    >>> (b / a).quantize(TWOPLACES)     # And quantize division
    Decimal('0.03')

In developing fixed-point applications, it is convenient to define functions
Christian Heimes's avatar
Christian Heimes committed
2003
to handle the :meth:`quantize` step:
Christian Heimes's avatar
Christian Heimes committed
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013

    >>> def mul(x, y, fp=TWOPLACES):
    ...     return (x * y).quantize(fp)
    >>> def div(x, y, fp=TWOPLACES):
    ...     return (x / y).quantize(fp)

    >>> mul(a, b)                       # Automatically preserve fixed-point
    Decimal('325.62')
    >>> div(b, a)
    Decimal('0.03')
2014 2015 2016 2017 2018 2019 2020

Q. There are many ways to express the same value.  The numbers :const:`200`,
:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
various precisions. Is there a way to transform them to a single recognizable
canonical value?

A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimes's avatar
Christian Heimes committed
2021
representative:
2022 2023 2024

   >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
   >>> [v.normalize() for v in values]
Christian Heimes's avatar
Christian Heimes committed
2025
   [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
2026 2027 2028 2029 2030 2031 2032 2033 2034

Q. Some decimal values always print with exponential notation.  Is there a way
to get a non-exponential representation?

A. For some values, exponential notation is the only way to express the number
of significant places in the coefficient.  For example, expressing
:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
original's two-place significance.

Christian Heimes's avatar
Christian Heimes committed
2035
If an application does not care about tracking significance, it is easy to
Christian Heimes's avatar
Christian Heimes committed
2036
remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimes's avatar
Christian Heimes committed
2037
value unchanged:
Christian Heimes's avatar
Christian Heimes committed
2038 2039 2040 2041 2042 2043 2044

    >>> def remove_exponent(d):
    ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

    >>> remove_exponent(Decimal('5E+3'))
    Decimal('5000')

2045 2046
Q. Is there a way to convert a regular float to a :class:`Decimal`?

2047
A. Yes, any binary floating point number can be exactly expressed as a
2048 2049
Decimal though an exact conversion may take more precision than intuition would
suggest:
2050

Christian Heimes's avatar
Christian Heimes committed
2051 2052
.. doctest::

2053
    >>> Decimal(math.pi)
Christian Heimes's avatar
Christian Heimes committed
2054
    Decimal('3.141592653589793115997963468544185161590576171875')
2055

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
Q. Within a complex calculation, how can I make sure that I haven't gotten a
spurious result because of insufficient precision or rounding anomalies.

A. The decimal module makes it easy to test results.  A best practice is to
re-run calculations using greater precision and with various rounding modes.
Widely differing results indicate insufficient precision, rounding mode issues,
ill-conditioned inputs, or a numerically unstable algorithm.

Q. I noticed that context precision is applied to the results of operations but
not to the inputs.  Is there anything to watch out for when mixing values of
different precisions?

A. Yes.  The principle is that all values are considered to be exact and so is
the arithmetic on those values.  Only the results are rounded.  The advantage
for inputs is that "what you type is what you get".  A disadvantage is that the
Christian Heimes's avatar
Christian Heimes committed
2071 2072 2073
results can look odd if you forget that the inputs haven't been rounded:

.. doctest:: newcontext
2074 2075

   >>> getcontext().prec = 3
Christian Heimes's avatar
Christian Heimes committed
2076
   >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes's avatar
Christian Heimes committed
2077
   Decimal('5.21')
Christian Heimes's avatar
Christian Heimes committed
2078
   >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes's avatar
Christian Heimes committed
2079
   Decimal('5.20')
2080 2081

The solution is either to increase precision or to force rounding of inputs
Christian Heimes's avatar
Christian Heimes committed
2082 2083 2084
using the unary plus operation:

.. doctest:: newcontext
2085 2086 2087

   >>> getcontext().prec = 3
   >>> +Decimal('1.23456789')      # unary plus triggers rounding
Christian Heimes's avatar
Christian Heimes committed
2088
   Decimal('1.23')
2089 2090

Alternatively, inputs can be rounded upon creation using the
Christian Heimes's avatar
Christian Heimes committed
2091
:meth:`Context.create_decimal` method:
2092 2093

   >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes's avatar
Christian Heimes committed
2094
   Decimal('1.2345')
2095