Debian Codegraph @

Doc/library/decimal.rst

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