blob: 8d457e192659f0cd1dcdefa65da55982fc79e581 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
Raymond Hettinger13a70752008-02-10 07:21:09 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
8
9.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
10.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
11.. moduleauthor:: Raymond Hettinger <python at rcn.com>
12.. moduleauthor:: Aahz <aahz at pobox.com>
13.. moduleauthor:: Tim Peters <tim.one at comcast.net>
14
15
16.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
17
Georg Brandl8ec7f652007-08-15 14:28:01 +000018.. versionadded:: 2.4
19
Georg Brandl9f662322008-03-22 11:47:10 +000020.. import modules for testing inline doctests with the Sphinx doctest builder
Georg Brandl17baef02008-03-22 10:56:23 +000021.. testsetup:: *
22
Georg Brandl9f662322008-03-22 11:47:10 +000023 import decimal
24 import math
Georg Brandl17baef02008-03-22 10:56:23 +000025 from decimal import *
Georg Brandl9f662322008-03-22 11:47:10 +000026 # make sure each group gets a fresh context
27 setcontext(Context())
Georg Brandl17baef02008-03-22 10:56:23 +000028
Georg Brandl8ec7f652007-08-15 14:28:01 +000029The :mod:`decimal` module provides support for decimal floating point
Facundo Batista7c82a3e92007-09-14 18:58:34 +000030arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Raymond Hettinger13a70752008-02-10 07:21:09 +000032* Decimal "is based on a floating-point model which was designed with people
33 in mind, and necessarily has a paramount guiding principle -- computers must
34 provide an arithmetic that works in the same way as the arithmetic that
35 people learn at school." -- excerpt from the decimal arithmetic specification.
36
Georg Brandl8ec7f652007-08-15 14:28:01 +000037* Decimal numbers can be represented exactly. In contrast, numbers like
Terry Jan Reedy4ba76b62012-01-13 23:41:31 -050038 :const:`1.1` and :const:`2.2` do not have exact representations in binary
Mark Dickinson6b87f112009-11-24 14:27:02 +000039 floating point. End users typically would not expect ``1.1 + 2.2`` to display
40 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl8ec7f652007-08-15 14:28:01 +000041
42* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Facundo Batista7c82a3e92007-09-14 18:58:34 +000043 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl8ec7f652007-08-15 14:28:01 +000044 is :const:`5.5511151231257827e-017`. While near to zero, the differences
45 prevent reliable equality testing and differences can accumulate. For this
Raymond Hettinger13a70752008-02-10 07:21:09 +000046 reason, decimal is preferred in accounting applications which have strict
Georg Brandl8ec7f652007-08-15 14:28:01 +000047 equality invariants.
48
49* The decimal module incorporates a notion of significant places so that ``1.30
50 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
51 This is the customary presentation for monetary applications. For
52 multiplication, the "schoolbook" approach uses all the figures in the
53 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
54 1.20`` gives :const:`1.5600`.
55
56* Unlike hardware based binary floating point, the decimal module has a user
Facundo Batista7c82a3e92007-09-14 18:58:34 +000057 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl17baef02008-03-22 10:56:23 +000058 a given problem:
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
Mark Dickinson03335172010-11-07 11:29:03 +000060 >>> from decimal import *
Georg Brandl8ec7f652007-08-15 14:28:01 +000061 >>> getcontext().prec = 6
62 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000063 Decimal('0.142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +000064 >>> getcontext().prec = 28
65 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000066 Decimal('0.1428571428571428571428571429')
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
68* Both binary and decimal floating point are implemented in terms of published
69 standards. While the built-in float type exposes only a modest portion of its
70 capabilities, the decimal module exposes all required parts of the standard.
71 When needed, the programmer has full control over rounding and signal handling.
Raymond Hettinger13a70752008-02-10 07:21:09 +000072 This includes an option to enforce exact arithmetic by using exceptions
73 to block any inexact operations.
74
75* The decimal module was designed to support "without prejudice, both exact
76 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
77 and rounded floating-point arithmetic." -- excerpt from the decimal
78 arithmetic specification.
Georg Brandl8ec7f652007-08-15 14:28:01 +000079
80The module design is centered around three concepts: the decimal number, the
81context for arithmetic, and signals.
82
83A decimal number is immutable. It has a sign, coefficient digits, and an
84exponent. To preserve significance, the coefficient digits do not truncate
Facundo Batista7c82a3e92007-09-14 18:58:34 +000085trailing zeros. Decimals also include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +000086:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
87differentiates :const:`-0` from :const:`+0`.
88
89The context for arithmetic is an environment specifying precision, rounding
90rules, limits on exponents, flags indicating the results of operations, and trap
91enablers which determine whether signals are treated as exceptions. Rounding
92options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
93:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +000094:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96Signals are groups of exceptional conditions arising during the course of
97computation. Depending on the needs of the application, signals may be ignored,
98considered as informational, or treated as exceptions. The signals in the
99decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
100:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
101:const:`Overflow`, and :const:`Underflow`.
102
103For each signal there is a flag and a trap enabler. When a signal is
Mark Dickinson1840c1a2008-05-03 18:23:14 +0000104encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000105set to one, an exception is raised. Flags are sticky, so the user needs to
106reset them before monitoring a calculation.
107
108
109.. seealso::
110
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000111 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettingerf345a212009-03-10 01:07:30 +0000112 Specification <http://speleotrove.com/decimal/>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
Georg Brandlb19be572007-12-29 10:57:00 +0000114.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
116
117.. _decimal-tutorial:
118
119Quick-start Tutorial
120--------------------
121
122The usual start to using decimals is importing the module, viewing the current
123context with :func:`getcontext` and, if necessary, setting new values for
Georg Brandl9f662322008-03-22 11:47:10 +0000124precision, rounding, or enabled traps::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126 >>> from decimal import *
127 >>> getcontext()
128 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000129 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
130 InvalidOperation])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000131
132 >>> getcontext().prec = 7 # Set a new precision
133
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000134Decimal instances can be constructed from integers, strings, floats, or tuples.
135Construction from an integer or a float performs an exact conversion of the
136value of that integer or float. Decimal numbers include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000137:const:`NaN` which stands for "Not a number", positive and negative
Georg Brandl17baef02008-03-22 10:56:23 +0000138:const:`Infinity`, and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000140 >>> getcontext().prec = 28
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000142 Decimal('10')
143 >>> Decimal('3.14')
144 Decimal('3.14')
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000145 >>> Decimal(3.14)
146 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000148 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000150 Decimal('1.41421356237')
151 >>> Decimal(2) ** Decimal('0.5')
152 Decimal('1.414213562373095048801688724')
153 >>> Decimal('NaN')
154 Decimal('NaN')
155 >>> Decimal('-Infinity')
156 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157
158The significance of a new Decimal is determined solely by the number of digits
159input. Context precision and rounding only come into play during arithmetic
Georg Brandl17baef02008-03-22 10:56:23 +0000160operations.
161
162.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163
164 >>> getcontext().prec = 6
165 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000166 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000168 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000170 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171 >>> getcontext().rounding = ROUND_UP
172 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000173 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
175Decimals interact well with much of the rest of Python. Here is a small decimal
Georg Brandl9f662322008-03-22 11:47:10 +0000176floating point flying circus:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
Georg Brandl838b4b02008-03-22 13:07:06 +0000178.. doctest::
179 :options: +NORMALIZE_WHITESPACE
180
Georg Brandl8ec7f652007-08-15 14:28:01 +0000181 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
182 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000183 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000185 Decimal('0.03')
Georg Brandl838b4b02008-03-22 13:07:06 +0000186 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000187 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
188 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000190 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191 >>> a,b,c = data[:3]
192 >>> str(a)
193 '1.34'
194 >>> float(a)
Mark Dickinson6b87f112009-11-24 14:27:02 +0000195 1.34
Georg Brandl8ec7f652007-08-15 14:28:01 +0000196 >>> round(a, 1) # round() first converts to binary floating point
197 1.3
198 >>> int(a)
199 1
200 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000201 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000203 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000205 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206
Georg Brandl9f662322008-03-22 11:47:10 +0000207And some mathematical functions are also available to Decimal:
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000208
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000209 >>> getcontext().prec = 28
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000210 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000211 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000212 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000213 Decimal('2.718281828459045235360287471')
214 >>> Decimal('10').ln()
215 Decimal('2.302585092994045684017991455')
216 >>> Decimal('10').log10()
217 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000218
Georg Brandl8ec7f652007-08-15 14:28:01 +0000219The :meth:`quantize` method rounds a number to a fixed exponent. This method is
220useful for monetary applications that often round results to a fixed number of
Georg Brandl9f662322008-03-22 11:47:10 +0000221places:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000222
223 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000224 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000226 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227
228As shown above, the :func:`getcontext` function accesses the current context and
229allows the settings to be changed. This approach meets the needs of most
230applications.
231
232For more advanced work, it may be useful to create alternate contexts using the
233Context() constructor. To make an alternate active, use the :func:`setcontext`
234function.
235
Serhiy Storchaka251aede2015-03-14 21:32:41 +0200236In accordance with the standard, the :mod:`decimal` module provides two ready to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
238former is especially useful for debugging because many of the traps are
Georg Brandl9f662322008-03-22 11:47:10 +0000239enabled:
240
241.. doctest:: newcontext
242 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243
244 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
245 >>> setcontext(myothercontext)
246 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000247 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
249 >>> ExtendedContext
250 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
251 capitals=1, flags=[], traps=[])
252 >>> setcontext(ExtendedContext)
253 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000254 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000256 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257
258 >>> setcontext(BasicContext)
259 >>> Decimal(42) / Decimal(0)
260 Traceback (most recent call last):
261 File "<pyshell#143>", line 1, in -toplevel-
262 Decimal(42) / Decimal(0)
263 DivisionByZero: x / 0
264
265Contexts also have signal flags for monitoring exceptional conditions
266encountered during computations. The flags remain set until explicitly cleared,
267so it is best to clear the flags before each set of monitored computations by
268using the :meth:`clear_flags` method. ::
269
270 >>> setcontext(ExtendedContext)
271 >>> getcontext().clear_flags()
272 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000273 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000274 >>> getcontext()
275 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000276 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278The *flags* entry shows that the rational approximation to :const:`Pi` was
279rounded (digits beyond the context precision were thrown away) and that the
280result is inexact (some of the discarded digits were non-zero).
281
282Individual traps are set using the dictionary in the :attr:`traps` field of a
Georg Brandl9f662322008-03-22 11:47:10 +0000283context:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
Georg Brandl9f662322008-03-22 11:47:10 +0000285.. doctest:: newcontext
286
287 >>> setcontext(ExtendedContext)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000288 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000289 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290 >>> getcontext().traps[DivisionByZero] = 1
291 >>> Decimal(1) / Decimal(0)
292 Traceback (most recent call last):
293 File "<pyshell#112>", line 1, in -toplevel-
294 Decimal(1) / Decimal(0)
295 DivisionByZero: x / 0
296
297Most programs adjust the current context only once, at the beginning of the
298program. And, in many applications, data is converted to :class:`Decimal` with
299a single cast inside a loop. With context set and decimals created, the bulk of
300the program manipulates the data no differently than with other Python numeric
301types.
302
Georg Brandlb19be572007-12-29 10:57:00 +0000303.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
305
306.. _decimal-decimal:
307
308Decimal objects
309---------------
310
311
312.. class:: Decimal([value [, context]])
313
Georg Brandlb19be572007-12-29 10:57:00 +0000314 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315
Raymond Hettingered171ab2010-04-02 18:39:24 +0000316 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000317 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000318 string, it should conform to the decimal numeric string syntax after leading
319 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320
321 sign ::= '+' | '-'
322 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
323 indicator ::= 'e' | 'E'
324 digits ::= digit [digit]...
325 decimal-part ::= digits '.' [digits] | ['.'] digits
326 exponent-part ::= indicator [sign] digits
327 infinity ::= 'Infinity' | 'Inf'
328 nan ::= 'NaN' [digits] | 'sNaN' [digits]
329 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000330 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl8ec7f652007-08-15 14:28:01 +0000331
Mark Dickinson4326ad82009-08-02 10:59:36 +0000332 If *value* is a unicode string then other Unicode decimal digits
333 are also permitted where ``digit`` appears above. These include
334 decimal digits from various other alphabets (for example,
335 Arabic-Indic and Devanāgarī digits) along with the fullwidth digits
336 ``u'\uff10'`` through ``u'\uff19'``.
337
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338 If *value* is a :class:`tuple`, it should have three components, a sign
339 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
340 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000341 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342
Raymond Hettingered171ab2010-04-02 18:39:24 +0000343 If *value* is a :class:`float`, the binary floating point value is losslessly
344 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000345 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
346 converts to
347 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettingered171ab2010-04-02 18:39:24 +0000348
Georg Brandl8ec7f652007-08-15 14:28:01 +0000349 The *context* precision does not affect how many digits are stored. That is
350 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000351 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352 only three.
353
354 The purpose of the *context* argument is determining what to do if *value* is a
355 malformed string. If the context traps :const:`InvalidOperation`, an exception
356 is raised; otherwise, the constructor returns a new Decimal with the value of
357 :const:`NaN`.
358
359 Once constructed, :class:`Decimal` objects are immutable.
360
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000361 .. versionchanged:: 2.6
362 leading and trailing whitespace characters are permitted when
363 creating a Decimal instance from a string.
364
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000365 .. versionchanged:: 2.7
Ezio Melotti6f65d2d2010-04-04 23:21:53 +0000366 The argument to the constructor is now permitted to be a :class:`float` instance.
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000367
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000368 Decimal floating point objects share many properties with the other built-in
369 numeric types such as :class:`float` and :class:`int`. All of the usual math
370 operations and special methods apply. Likewise, decimal objects can be
371 copied, pickled, printed, used as dictionary keys, used as set elements,
372 compared, sorted, and coerced to another type (such as :class:`float` or
373 :class:`long`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374
Mark Dickinson0d187312012-11-18 10:20:28 +0000375 There are some small differences between arithmetic on Decimal objects and
376 arithmetic on integers and floats. When the remainder operator ``%`` is
377 applied to Decimal objects, the sign of the result is the sign of the
378 *dividend* rather than the sign of the divisor::
379
380 >>> (-7) % 4
381 1
382 >>> Decimal(-7) % Decimal(4)
383 Decimal('-3')
384
385 The integer division operator ``//`` behaves analogously, returning the
386 integer part of the true quotient (truncating towards zero) rather than its
Mark Dickinson3c9181b2012-11-18 10:41:29 +0000387 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::
Mark Dickinson0d187312012-11-18 10:20:28 +0000388
389 >>> -7 // 4
390 -2
391 >>> Decimal(-7) // Decimal(4)
392 Decimal('-1')
393
394 The ``%`` and ``//`` operators implement the ``remainder`` and
395 ``divide-integer`` operations (respectively) as described in the
396 specification.
397
Mark Dickinson99d80962010-04-02 08:53:22 +0000398 Decimal objects cannot generally be combined with floats in
399 arithmetic operations: an attempt to add a :class:`Decimal` to a
400 :class:`float`, for example, will raise a :exc:`TypeError`.
401 There's one exception to this rule: it's possible to use Python's
402 comparison operators to compare a :class:`float` instance ``x``
403 with a :class:`Decimal` instance ``y``. Without this exception,
404 comparisons between :class:`Decimal` and :class:`float` instances
405 would follow the general rules for comparing objects of different
406 types described in the :ref:`expressions` section of the reference
407 manual, leading to confusing results.
408
409 .. versionchanged:: 2.7
410 A comparison between a :class:`float` instance ``x`` and a
411 :class:`Decimal` instance ``y`` now returns a result based on
412 the values of ``x`` and ``y``. In earlier versions ``x < y``
413 returned the same (arbitrary) result for any :class:`Decimal`
414 instance ``x`` and any :class:`float` instance ``y``.
415
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000416 In addition to the standard numeric properties, decimal floating point
417 objects also have a number of specialized methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000418
419
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000420 .. method:: adjusted()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000421
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000422 Return the adjusted exponent after shifting out the coefficient's
423 rightmost digits until only the lead digit remains:
424 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
425 position of the most significant digit with respect to the decimal point.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
427
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000428 .. method:: as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000430 Return a :term:`named tuple` representation of the number:
431 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandle3c3db52008-01-11 09:55:53 +0000432
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000433 .. versionchanged:: 2.6
434 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
436
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000437 .. method:: canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000438
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000439 Return the canonical encoding of the argument. Currently, the encoding of
440 a :class:`Decimal` instance is always canonical, so this operation returns
441 its argument unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000442
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000443 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000444
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000445 .. method:: compare(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000446
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000447 Compare the values of two Decimal instances. This operation behaves in
448 the same way as the usual comparison method :meth:`__cmp__`, except that
449 :meth:`compare` returns a Decimal instance rather than an integer, and if
450 either operand is a NaN then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000452 a or b is a NaN ==> Decimal('NaN')
453 a < b ==> Decimal('-1')
454 a == b ==> Decimal('0')
455 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000457 .. method:: compare_signal(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000458
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000459 This operation is identical to the :meth:`compare` method, except that all
460 NaNs signal. That is, if neither operand is a signaling NaN then any
461 quiet NaN operand is treated as though it were a signaling NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000462
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000463 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000464
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000465 .. method:: compare_total(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000466
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000467 Compare two operands using their abstract representation rather than their
468 numerical value. Similar to the :meth:`compare` method, but the result
469 gives a total ordering on :class:`Decimal` instances. Two
470 :class:`Decimal` instances with the same numeric value but different
471 representations compare unequal in this ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000472
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000473 >>> Decimal('12.0').compare_total(Decimal('12'))
474 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000475
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000476 Quiet and signaling NaNs are also included in the total ordering. The
477 result of this function is ``Decimal('0')`` if both operands have the same
478 representation, ``Decimal('-1')`` if the first operand is lower in the
479 total order than the second, and ``Decimal('1')`` if the first operand is
480 higher in the total order than the second operand. See the specification
481 for details of the total order.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000482
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000483 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000484
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000485 .. method:: compare_total_mag(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000486
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000487 Compare two operands using their abstract representation rather than their
488 value as in :meth:`compare_total`, but ignoring the sign of each operand.
489 ``x.compare_total_mag(y)`` is equivalent to
490 ``x.copy_abs().compare_total(y.copy_abs())``.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000491
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000492 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000493
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000494 .. method:: conjugate()
495
496 Just returns self, this method is only to comply with the Decimal
497 Specification.
498
499 .. versionadded:: 2.6
500
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000501 .. method:: copy_abs()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000502
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000503 Return the absolute value of the argument. This operation is unaffected
504 by the context and is quiet: no flags are changed and no rounding is
505 performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000506
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000507 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000508
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000509 .. method:: copy_negate()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000510
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000511 Return the negation of the argument. This operation is unaffected by the
512 context and is quiet: no flags are changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000513
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000514 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000515
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000516 .. method:: copy_sign(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000517
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000518 Return a copy of the first operand with the sign set to be the same as the
519 sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000520
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000521 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
522 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000523
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000524 This operation is unaffected by the context and is quiet: no flags are
525 changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000526
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000527 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000528
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000529 .. method:: exp([context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000530
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000531 Return the value of the (natural) exponential function ``e**x`` at the
532 given number. The result is correctly rounded using the
533 :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000534
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000535 >>> Decimal(1).exp()
536 Decimal('2.718281828459045235360287471')
537 >>> Decimal(321).exp()
538 Decimal('2.561702493119680037517373933E+139')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000539
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000540 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000541
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000542 .. method:: from_float(f)
543
544 Classmethod that converts a float to a decimal number, exactly.
545
546 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
547 Since 0.1 is not exactly representable in binary floating point, the
548 value is stored as the nearest representable value which is
549 `0x1.999999999999ap-4`. That equivalent value in decimal is
550 `0.1000000000000000055511151231257827021181583404541015625`.
551
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000552 .. note:: From Python 2.7 onwards, a :class:`Decimal` instance
553 can also be constructed directly from a :class:`float`.
554
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000555 .. doctest::
556
557 >>> Decimal.from_float(0.1)
558 Decimal('0.1000000000000000055511151231257827021181583404541015625')
559 >>> Decimal.from_float(float('nan'))
560 Decimal('NaN')
561 >>> Decimal.from_float(float('inf'))
562 Decimal('Infinity')
563 >>> Decimal.from_float(float('-inf'))
564 Decimal('-Infinity')
565
566 .. versionadded:: 2.7
567
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000568 .. method:: fma(other, third[, context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000569
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000570 Fused multiply-add. Return self*other+third with no rounding of the
571 intermediate product self*other.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000572
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000573 >>> Decimal(2).fma(3, 5)
574 Decimal('11')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000575
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000576 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000577
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000578 .. method:: is_canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000579
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000580 Return :const:`True` if the argument is canonical and :const:`False`
581 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
582 this operation always returns :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000583
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000584 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000585
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000586 .. method:: is_finite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000587
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000588 Return :const:`True` if the argument is a finite number, and
589 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000590
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000591 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000592
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000593 .. method:: is_infinite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000594
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000595 Return :const:`True` if the argument is either positive or negative
596 infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000597
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000598 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000599
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000600 .. method:: is_nan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000601
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000602 Return :const:`True` if the argument is a (quiet or signaling) NaN and
603 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000604
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000605 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000606
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000607 .. method:: is_normal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000608
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000609 Return :const:`True` if the argument is a *normal* finite non-zero
610 number with an adjusted exponent greater than or equal to *Emin*.
611 Return :const:`False` if the argument is zero, subnormal, infinite or a
612 NaN. Note, the term *normal* is used here in a different sense with
613 the :meth:`normalize` method which is used to create canonical values.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000614
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000615 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000616
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000617 .. method:: is_qnan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000618
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000619 Return :const:`True` if the argument is a quiet NaN, and
620 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000621
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000622 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000623
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000624 .. method:: is_signed()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000625
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000626 Return :const:`True` if the argument has a negative sign and
627 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000628
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000629 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000630
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000631 .. method:: is_snan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000632
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000633 Return :const:`True` if the argument is a signaling NaN and :const:`False`
634 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000635
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000636 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000637
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000638 .. method:: is_subnormal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000639
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000640 Return :const:`True` if the argument is subnormal, and :const:`False`
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000641 otherwise. A number is subnormal is if it is nonzero, finite, and has an
642 adjusted exponent less than *Emin*.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000643
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000644 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000645
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000646 .. method:: is_zero()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000647
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000648 Return :const:`True` if the argument is a (positive or negative) zero and
649 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000650
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000651 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000652
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000653 .. method:: ln([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000654
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000655 Return the natural (base e) logarithm of the operand. The result is
656 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000657
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000658 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000659
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000660 .. method:: log10([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000661
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000662 Return the base ten logarithm of the operand. The result is correctly
663 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000664
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000665 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000666
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000667 .. method:: logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000668
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000669 For a nonzero number, return the adjusted exponent of its operand as a
670 :class:`Decimal` instance. If the operand is a zero then
671 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
672 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
673 returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000674
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000675 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000676
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000677 .. method:: logical_and(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000678
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000679 :meth:`logical_and` is a logical operation which takes two *logical
680 operands* (see :ref:`logical_operands_label`). The result is the
681 digit-wise ``and`` of the two operands.
682
683 .. versionadded:: 2.6
684
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000685 .. method:: logical_invert([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000686
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000687 :meth:`logical_invert` is a logical operation. The
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000688 result is the digit-wise inversion of the operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000689
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000690 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000691
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000692 .. method:: logical_or(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000693
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000694 :meth:`logical_or` is a logical operation which takes two *logical
695 operands* (see :ref:`logical_operands_label`). The result is the
696 digit-wise ``or`` of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000697
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000698 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000699
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000700 .. method:: logical_xor(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000701
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000702 :meth:`logical_xor` is a logical operation which takes two *logical
703 operands* (see :ref:`logical_operands_label`). The result is the
704 digit-wise exclusive or of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000705
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000706 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000707
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000708 .. method:: max(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000709
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000710 Like ``max(self, other)`` except that the context rounding rule is applied
711 before returning and that :const:`NaN` values are either signaled or
712 ignored (depending on the context and whether they are signaling or
713 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000714
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000715 .. method:: max_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000716
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000717 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000718 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000719
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000720 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000722 .. method:: min(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000723
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000724 Like ``min(self, other)`` except that the context rounding rule is applied
725 before returning and that :const:`NaN` values are either signaled or
726 ignored (depending on the context and whether they are signaling or
727 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000728
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000729 .. method:: min_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000730
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000731 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000732 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000733
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000734 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000735
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000736 .. method:: next_minus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000737
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000738 Return the largest number representable in the given context (or in the
739 current thread's context if no context is given) that is smaller than the
740 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000741
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000742 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000743
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000744 .. method:: next_plus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000745
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000746 Return the smallest number representable in the given context (or in the
747 current thread's context if no context is given) that is larger than the
748 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000749
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000750 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000751
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000752 .. method:: next_toward(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000753
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000754 If the two operands are unequal, return the number closest to the first
755 operand in the direction of the second operand. If both operands are
756 numerically equal, return a copy of the first operand with the sign set to
757 be the same as the sign of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000758
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000759 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000760
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000761 .. method:: normalize([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000762
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000763 Normalize the number by stripping the rightmost trailing zeros and
764 converting any result equal to :const:`Decimal('0')` to
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700765 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000766 of an equivalence class. For example, ``Decimal('32.100')`` and
767 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
768 ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000769
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000770 .. method:: number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000771
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000772 Return a string describing the *class* of the operand. The returned value
773 is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000774
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000775 * ``"-Infinity"``, indicating that the operand is negative infinity.
776 * ``"-Normal"``, indicating that the operand is a negative normal number.
777 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
778 * ``"-Zero"``, indicating that the operand is a negative zero.
779 * ``"+Zero"``, indicating that the operand is a positive zero.
780 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
781 * ``"+Normal"``, indicating that the operand is a positive normal number.
782 * ``"+Infinity"``, indicating that the operand is positive infinity.
783 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
784 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000786 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000787
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000788 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000789
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000790 Return a value equal to the first operand after rounding and having the
791 exponent of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000792
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000793 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
794 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000795
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000796 Unlike other operations, if the length of the coefficient after the
797 quantize operation would be greater than precision, then an
798 :const:`InvalidOperation` is signaled. This guarantees that, unless there
799 is an error condition, the quantized exponent is always equal to that of
800 the right-hand operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000801
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000802 Also unlike other operations, quantize never signals Underflow, even if
803 the result is subnormal and inexact.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000804
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000805 If the exponent of the second operand is larger than that of the first
806 then rounding may be necessary. In this case, the rounding mode is
807 determined by the ``rounding`` argument if given, else by the given
808 ``context`` argument; if neither argument is given the rounding mode of
809 the current thread's context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000810
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000811 If *watchexp* is set (default), then an error is returned whenever the
812 resulting exponent is greater than :attr:`Emax` or less than
813 :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000814
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000815 .. method:: radix()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000816
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000817 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
818 class does all its arithmetic. Included for compatibility with the
819 specification.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000820
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000821 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000823 .. method:: remainder_near(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000824
Mark Dickinson89e8f542012-10-31 19:44:09 +0000825 Return the remainder from dividing *self* by *other*. This differs from
826 ``self % other`` in that the sign of the remainder is chosen so as to
827 minimize its absolute value. More precisely, the return value is
828 ``self - n * other`` where ``n`` is the integer nearest to the exact
829 value of ``self / other``, and if two integers are equally near then the
830 even one is chosen.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831
Mark Dickinson89e8f542012-10-31 19:44:09 +0000832 If the result is zero then its sign will be the sign of *self*.
833
834 >>> Decimal(18).remainder_near(Decimal(10))
835 Decimal('-2')
836 >>> Decimal(25).remainder_near(Decimal(10))
837 Decimal('5')
838 >>> Decimal(35).remainder_near(Decimal(10))
839 Decimal('-5')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000840
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000841 .. method:: rotate(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000842
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000843 Return the result of rotating the digits of the first operand by an amount
844 specified by the second operand. The second operand must be an integer in
845 the range -precision through precision. The absolute value of the second
846 operand gives the number of places to rotate. If the second operand is
847 positive then rotation is to the left; otherwise rotation is to the right.
848 The coefficient of the first operand is padded on the left with zeros to
849 length precision if necessary. The sign and exponent of the first operand
850 are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000851
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000852 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000853
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000854 .. method:: same_quantum(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000855
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000856 Test whether self and other have the same exponent or whether both are
857 :const:`NaN`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000858
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000859 .. method:: scaleb(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000860
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000861 Return the first operand with exponent adjusted by the second.
862 Equivalently, return the first operand multiplied by ``10**other``. The
863 second operand must be an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000864
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000865 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000866
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000867 .. method:: shift(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000868
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000869 Return the result of shifting the digits of the first operand by an amount
870 specified by the second operand. The second operand must be an integer in
871 the range -precision through precision. The absolute value of the second
872 operand gives the number of places to shift. If the second operand is
873 positive then the shift is to the left; otherwise the shift is to the
874 right. Digits shifted into the coefficient are zeros. The sign and
875 exponent of the first operand are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000876
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000877 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000878
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000879 .. method:: sqrt([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000880
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000881 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000882
883
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000884 .. method:: to_eng_string([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000885
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000886 Convert to an engineering-type string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000887
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000888 Engineering notation has an exponent which is a multiple of 3, so there
889 are up to 3 digits left of the decimal place. For example, converts
Martin Panter4ed35fc2015-10-10 10:52:35 +0000890 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000891
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000892 .. method:: to_integral([rounding[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000893
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000894 Identical to the :meth:`to_integral_value` method. The ``to_integral``
895 name has been kept for compatibility with older versions.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000896
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000897 .. method:: to_integral_exact([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000898
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000899 Round to the nearest integer, signaling :const:`Inexact` or
900 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
901 determined by the ``rounding`` parameter if given, else by the given
902 ``context``. If neither parameter is given then the rounding mode of the
903 current context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000904
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000905 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000906
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000907 .. method:: to_integral_value([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000908
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000909 Round to the nearest integer without signaling :const:`Inexact` or
910 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
911 rounding method in either the supplied *context* or the current context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000912
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000913 .. versionchanged:: 2.6
914 renamed from ``to_integral`` to ``to_integral_value``. The old name
915 remains valid for compatibility.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000916
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000917.. _logical_operands_label:
918
919Logical operands
920^^^^^^^^^^^^^^^^
921
922The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
923and :meth:`logical_xor` methods expect their arguments to be *logical
924operands*. A *logical operand* is a :class:`Decimal` instance whose
925exponent and sign are both zero, and whose digits are all either
926:const:`0` or :const:`1`.
927
Georg Brandlb19be572007-12-29 10:57:00 +0000928.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000929
930
931.. _decimal-context:
932
933Context objects
934---------------
935
936Contexts are environments for arithmetic operations. They govern precision, set
937rules for rounding, determine which signals are treated as exceptions, and limit
938the range for exponents.
939
940Each thread has its own current context which is accessed or changed using the
941:func:`getcontext` and :func:`setcontext` functions:
942
943
944.. function:: getcontext()
945
946 Return the current context for the active thread.
947
948
949.. function:: setcontext(c)
950
951 Set the current context for the active thread to *c*.
952
953Beginning with Python 2.5, you can also use the :keyword:`with` statement and
954the :func:`localcontext` function to temporarily change the active context.
955
956
957.. function:: localcontext([c])
958
959 Return a context manager that will set the current context for the active thread
960 to a copy of *c* on entry to the with-statement and restore the previous context
961 when exiting the with-statement. If no context is specified, a copy of the
962 current context is used.
963
964 .. versionadded:: 2.5
965
966 For example, the following code sets the current decimal precision to 42 places,
967 performs a calculation, and then automatically restores the previous context::
968
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969 from decimal import localcontext
970
971 with localcontext() as ctx:
972 ctx.prec = 42 # Perform a high precision calculation
973 s = calculate_something()
974 s = +s # Round the final result back to the default precision
975
Raymond Hettinger56f5c382012-05-11 12:50:11 -0700976 with localcontext(BasicContext): # temporarily use the BasicContext
977 print Decimal(1) / Decimal(7)
978 print Decimal(355) / Decimal(113)
979
Georg Brandl8ec7f652007-08-15 14:28:01 +0000980New contexts can also be created using the :class:`Context` constructor
981described below. In addition, the module provides three pre-made contexts:
982
983
984.. class:: BasicContext
985
986 This is a standard context defined by the General Decimal Arithmetic
987 Specification. Precision is set to nine. Rounding is set to
988 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
989 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
990 :const:`Subnormal`.
991
992 Because many of the traps are enabled, this context is useful for debugging.
993
994
995.. class:: ExtendedContext
996
997 This is a standard context defined by the General Decimal Arithmetic
998 Specification. Precision is set to nine. Rounding is set to
999 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
1000 exceptions are not raised during computations).
1001
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001002 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +00001003 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
1004 raising exceptions. This allows an application to complete a run in the
1005 presence of conditions that would otherwise halt the program.
1006
1007
1008.. class:: DefaultContext
1009
1010 This context is used by the :class:`Context` constructor as a prototype for new
1011 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Krah3d08d882010-05-29 12:54:35 +00001012 default for new contexts created by the :class:`Context` constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001013
1014 This context is most useful in multi-threaded environments. Changing one of the
1015 fields before threads are started has the effect of setting system-wide
1016 defaults. Changing the fields after threads have started is not recommended as
1017 it would require thread synchronization to prevent race conditions.
1018
1019 In single threaded environments, it is preferable to not use this context at
1020 all. Instead, simply create contexts explicitly as described below.
1021
1022 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
1023 for Overflow, InvalidOperation, and DivisionByZero.
1024
1025In addition to the three supplied contexts, new contexts can be created with the
1026:class:`Context` constructor.
1027
1028
1029.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
1030
1031 Creates a new context. If a field is not specified or is :const:`None`, the
1032 default values are copied from the :const:`DefaultContext`. If the *flags*
1033 field is not specified or is :const:`None`, all flags are cleared.
1034
1035 The *prec* field is a positive integer that sets the precision for arithmetic
1036 operations in the context.
1037
1038 The *rounding* option is one of:
1039
1040 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
1041 * :const:`ROUND_DOWN` (towards zero),
1042 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
1043 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
1044 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
1045 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
1046 * :const:`ROUND_UP` (away from zero).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001047 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001048 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001049
1050 The *traps* and *flags* fields list any signals to be set. Generally, new
1051 contexts should only set traps and leave the flags clear.
1052
1053 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
1054 for exponents.
1055
1056 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
1057 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
1058 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1059
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001060 .. versionchanged:: 2.6
1061 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001062
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001063 The :class:`Context` class defines several general purpose methods as well as
1064 a large number of methods for doing arithmetic directly in a given context.
1065 In addition, for each of the :class:`Decimal` methods described above (with
1066 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson6d8effb2010-02-18 14:27:02 +00001067 a corresponding :class:`Context` method. For example, for a :class:`Context`
1068 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1069 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
1070 Python integer (an instance of :class:`int` or :class:`long`) anywhere that a
1071 Decimal instance is accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001072
1073
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001074 .. method:: clear_flags()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001076 Resets all of the flags to :const:`0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001077
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001078 .. method:: copy()
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001079
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001080 Return a duplicate of the context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001081
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001082 .. method:: copy_decimal(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001083
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001084 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001085
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001086 .. method:: create_decimal(num)
Georg Brandl9f662322008-03-22 11:47:10 +00001087
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001088 Creates a new Decimal instance from *num* but using *self* as
1089 context. Unlike the :class:`Decimal` constructor, the context precision,
1090 rounding method, flags, and traps are applied to the conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001092 This is useful because constants are often given to a greater precision
1093 than is needed by the application. Another benefit is that rounding
1094 immediately eliminates unintended effects from digits beyond the current
1095 precision. In the following example, using unrounded inputs means that
1096 adding zero to a sum can change the result:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001097
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001098 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001099
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001100 >>> getcontext().prec = 3
1101 >>> Decimal('3.4445') + Decimal('1.0023')
1102 Decimal('4.45')
1103 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1104 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001105
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001106 This method implements the to-number operation of the IBM specification.
1107 If the argument is a string, no leading or trailing whitespace is
1108 permitted.
1109
Georg Brandlaa5bb322009-01-03 19:44:48 +00001110 .. method:: create_decimal_from_float(f)
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001111
1112 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandla24067e2009-01-03 20:15:14 +00001113 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001114 the context precision, rounding method, flags, and traps are applied to
1115 the conversion.
1116
1117 .. doctest::
1118
Georg Brandlaa5bb322009-01-03 19:44:48 +00001119 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1120 >>> context.create_decimal_from_float(math.pi)
1121 Decimal('3.1415')
1122 >>> context = Context(prec=5, traps=[Inexact])
1123 >>> context.create_decimal_from_float(math.pi)
1124 Traceback (most recent call last):
1125 ...
1126 Inexact: None
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001127
1128 .. versionadded:: 2.7
1129
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001130 .. method:: Etiny()
1131
1132 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1133 value for subnormal results. When underflow occurs, the exponent is set
1134 to :const:`Etiny`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001135
1136
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001137 .. method:: Etop()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001138
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001139 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001140
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001141 The usual approach to working with decimals is to create :class:`Decimal`
1142 instances and then apply arithmetic operations which take place within the
1143 current context for the active thread. An alternative approach is to use
1144 context methods for calculating within a specific context. The methods are
1145 similar to those for the :class:`Decimal` class and are only briefly
1146 recounted here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001147
1148
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001149 .. method:: abs(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001150
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001151 Returns the absolute value of *x*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001152
1153
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001154 .. method:: add(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001155
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001156 Return the sum of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001157
1158
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001159 .. method:: canonical(x)
1160
1161 Returns the same Decimal object *x*.
1162
1163
1164 .. method:: compare(x, y)
1165
1166 Compares *x* and *y* numerically.
1167
1168
1169 .. method:: compare_signal(x, y)
1170
1171 Compares the values of the two operands numerically.
1172
1173
1174 .. method:: compare_total(x, y)
1175
1176 Compares two operands using their abstract representation.
1177
1178
1179 .. method:: compare_total_mag(x, y)
1180
1181 Compares two operands using their abstract representation, ignoring sign.
1182
1183
1184 .. method:: copy_abs(x)
1185
1186 Returns a copy of *x* with the sign set to 0.
1187
1188
1189 .. method:: copy_negate(x)
1190
1191 Returns a copy of *x* with the sign inverted.
1192
1193
1194 .. method:: copy_sign(x, y)
1195
1196 Copies the sign from *y* to *x*.
1197
1198
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001199 .. method:: divide(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001200
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001201 Return *x* divided by *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001202
1203
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001204 .. method:: divide_int(x, y)
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001205
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001206 Return *x* divided by *y*, truncated to an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001207
1208
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001209 .. method:: divmod(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001210
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001211 Divides two numbers and returns the integer part of the result.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001212
1213
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001214 .. method:: exp(x)
1215
1216 Returns `e ** x`.
1217
1218
1219 .. method:: fma(x, y, z)
1220
1221 Returns *x* multiplied by *y*, plus *z*.
1222
1223
1224 .. method:: is_canonical(x)
1225
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001226 Returns ``True`` if *x* is canonical; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001227
1228
1229 .. method:: is_finite(x)
1230
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001231 Returns ``True`` if *x* is finite; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001232
1233
1234 .. method:: is_infinite(x)
1235
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001236 Returns ``True`` if *x* is infinite; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001237
1238
1239 .. method:: is_nan(x)
1240
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001241 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001242
1243
1244 .. method:: is_normal(x)
1245
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001246 Returns ``True`` if *x* is a normal number; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001247
1248
1249 .. method:: is_qnan(x)
1250
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001251 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001252
1253
1254 .. method:: is_signed(x)
1255
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001256 Returns ``True`` if *x* is negative; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001257
1258
1259 .. method:: is_snan(x)
1260
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001261 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001262
1263
1264 .. method:: is_subnormal(x)
1265
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001266 Returns ``True`` if *x* is subnormal; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001267
1268
1269 .. method:: is_zero(x)
1270
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001271 Returns ``True`` if *x* is a zero; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001272
1273
1274 .. method:: ln(x)
1275
1276 Returns the natural (base e) logarithm of *x*.
1277
1278
1279 .. method:: log10(x)
1280
1281 Returns the base 10 logarithm of *x*.
1282
1283
1284 .. method:: logb(x)
1285
1286 Returns the exponent of the magnitude of the operand's MSD.
1287
1288
1289 .. method:: logical_and(x, y)
1290
Georg Brandle92818f2009-01-03 20:47:01 +00001291 Applies the logical operation *and* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001292
1293
1294 .. method:: logical_invert(x)
1295
1296 Invert all the digits in *x*.
1297
1298
1299 .. method:: logical_or(x, y)
1300
Georg Brandle92818f2009-01-03 20:47:01 +00001301 Applies the logical operation *or* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001302
1303
1304 .. method:: logical_xor(x, y)
1305
Georg Brandle92818f2009-01-03 20:47:01 +00001306 Applies the logical operation *xor* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001307
1308
1309 .. method:: max(x, y)
1310
1311 Compares two values numerically and returns the maximum.
1312
1313
1314 .. method:: max_mag(x, y)
1315
1316 Compares the values numerically with their sign ignored.
1317
1318
1319 .. method:: min(x, y)
1320
1321 Compares two values numerically and returns the minimum.
1322
1323
1324 .. method:: min_mag(x, y)
1325
1326 Compares the values numerically with their sign ignored.
1327
1328
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001329 .. method:: minus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001330
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001331 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001332
1333
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001334 .. method:: multiply(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001335
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001336 Return the product of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001337
1338
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001339 .. method:: next_minus(x)
1340
1341 Returns the largest representable number smaller than *x*.
1342
1343
1344 .. method:: next_plus(x)
1345
1346 Returns the smallest representable number larger than *x*.
1347
1348
1349 .. method:: next_toward(x, y)
1350
1351 Returns the number closest to *x*, in direction towards *y*.
1352
1353
1354 .. method:: normalize(x)
1355
1356 Reduces *x* to its simplest form.
1357
1358
1359 .. method:: number_class(x)
1360
1361 Returns an indication of the class of *x*.
1362
1363
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001364 .. method:: plus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001366 Plus corresponds to the unary prefix plus operator in Python. This
1367 operation applies the context precision and rounding, so it is *not* an
1368 identity operation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001369
1370
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001371 .. method:: power(x, y[, modulo])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001372
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001373 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001374
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001375 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1376 must be integral. The result will be inexact unless ``y`` is integral and
1377 the result is finite and can be expressed exactly in 'precision' digits.
1378 The result should always be correctly rounded, using the rounding mode of
1379 the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001380
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001381 With three arguments, compute ``(x**y) % modulo``. For the three argument
1382 form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001383
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001384 - all three arguments must be integral
1385 - ``y`` must be nonnegative
1386 - at least one of ``x`` or ``y`` must be nonzero
1387 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001388
Mark Dickinsonf5be4e62010-02-22 15:40:28 +00001389 The value resulting from ``Context.power(x, y, modulo)`` is
1390 equal to the value that would be obtained by computing ``(x**y)
1391 % modulo`` with unbounded precision, but is computed more
1392 efficiently. The exponent of the result is zero, regardless of
1393 the exponents of ``x``, ``y`` and ``modulo``. The result is
1394 always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001395
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001396 .. versionchanged:: 2.6
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001397 ``y`` may now be nonintegral in ``x**y``.
1398 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001399
1400
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001401 .. method:: quantize(x, y)
1402
1403 Returns a value equal to *x* (rounded), having the exponent of *y*.
1404
1405
1406 .. method:: radix()
1407
1408 Just returns 10, as this is Decimal, :)
1409
1410
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001411 .. method:: remainder(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001412
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001413 Returns the remainder from integer division.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001414
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001415 The sign of the result, if non-zero, is the same as that of the original
1416 dividend.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001417
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001418 .. method:: remainder_near(x, y)
1419
Georg Brandle92818f2009-01-03 20:47:01 +00001420 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1421 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001422
1423
1424 .. method:: rotate(x, y)
1425
1426 Returns a rotated copy of *x*, *y* times.
1427
1428
1429 .. method:: same_quantum(x, y)
1430
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001431 Returns ``True`` if the two operands have the same exponent.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001432
1433
1434 .. method:: scaleb (x, y)
1435
1436 Returns the first operand after adding the second value its exp.
1437
1438
1439 .. method:: shift(x, y)
1440
1441 Returns a shifted copy of *x*, *y* times.
1442
1443
1444 .. method:: sqrt(x)
1445
1446 Square root of a non-negative number to context precision.
1447
1448
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001449 .. method:: subtract(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001450
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001451 Return the difference between *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001452
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001453
1454 .. method:: to_eng_string(x)
1455
1456 Converts a number to a string, using scientific notation.
1457
1458
1459 .. method:: to_integral_exact(x)
1460
1461 Rounds to an integer.
1462
1463
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001464 .. method:: to_sci_string(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001465
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001466 Converts a number to a string using scientific notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001467
Georg Brandlb19be572007-12-29 10:57:00 +00001468.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001469
1470
1471.. _decimal-signals:
1472
1473Signals
1474-------
1475
1476Signals represent conditions that arise during computation. Each corresponds to
1477one context flag and one context trap enabler.
1478
Mark Dickinson1840c1a2008-05-03 18:23:14 +00001479The context flag is set whenever the condition is encountered. After the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001480computation, flags may be checked for informational purposes (for instance, to
1481determine whether a computation was exact). After checking the flags, be sure to
1482clear all flags before starting the next computation.
1483
1484If the context's trap enabler is set for the signal, then the condition causes a
1485Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1486is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1487condition.
1488
1489
1490.. class:: Clamped
1491
1492 Altered an exponent to fit representation constraints.
1493
1494 Typically, clamping occurs when an exponent falls outside the context's
1495 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001496 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001497
1498
1499.. class:: DecimalException
1500
1501 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1502
1503
1504.. class:: DivisionByZero
1505
1506 Signals the division of a non-infinite number by zero.
1507
1508 Can occur with division, modulo division, or when raising a number to a negative
1509 power. If this signal is not trapped, returns :const:`Infinity` or
1510 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1511
1512
1513.. class:: Inexact
1514
1515 Indicates that rounding occurred and the result is not exact.
1516
1517 Signals when non-zero digits were discarded during rounding. The rounded result
1518 is returned. The signal flag or trap is used to detect when results are
1519 inexact.
1520
1521
1522.. class:: InvalidOperation
1523
1524 An invalid operation was performed.
1525
1526 Indicates that an operation was requested that does not make sense. If not
1527 trapped, returns :const:`NaN`. Possible causes include::
1528
1529 Infinity - Infinity
1530 0 * Infinity
1531 Infinity / Infinity
1532 x % 0
1533 Infinity % x
1534 x._rescale( non-integer )
1535 sqrt(-x) and x > 0
1536 0 ** 0
1537 x ** (non-integer)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001538 x ** Infinity
Georg Brandl8ec7f652007-08-15 14:28:01 +00001539
1540
1541.. class:: Overflow
1542
1543 Numerical overflow.
1544
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001545 Indicates the exponent is larger than :attr:`Emax` after rounding has
1546 occurred. If not trapped, the result depends on the rounding mode, either
1547 pulling inward to the largest representable finite number or rounding outward
1548 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1549 are also signaled.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001550
1551
1552.. class:: Rounded
1553
1554 Rounding occurred though possibly no information was lost.
1555
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001556 Signaled whenever rounding discards digits; even if those digits are zero
1557 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1558 the result unchanged. This signal is used to detect loss of significant
1559 digits.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001560
1561
1562.. class:: Subnormal
1563
1564 Exponent was lower than :attr:`Emin` prior to rounding.
1565
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001566 Occurs when an operation result is subnormal (the exponent is too small). If
1567 not trapped, returns the result unchanged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001568
1569
1570.. class:: Underflow
1571
1572 Numerical underflow with result rounded to zero.
1573
1574 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1575 and :class:`Subnormal` are also signaled.
1576
1577The following table summarizes the hierarchy of signals::
1578
1579 exceptions.ArithmeticError(exceptions.StandardError)
1580 DecimalException
1581 Clamped
1582 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1583 Inexact
1584 Overflow(Inexact, Rounded)
1585 Underflow(Inexact, Rounded, Subnormal)
1586 InvalidOperation
1587 Rounded
1588 Subnormal
1589
Georg Brandlb19be572007-12-29 10:57:00 +00001590.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001591
1592
1593.. _decimal-notes:
1594
1595Floating Point Notes
1596--------------------
1597
1598
1599Mitigating round-off error with increased precision
1600^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1601
1602The use of decimal floating point eliminates decimal representation error
1603(making it possible to represent :const:`0.1` exactly); however, some operations
1604can still incur round-off error when non-zero digits exceed the fixed precision.
1605
1606The effects of round-off error can be amplified by the addition or subtraction
1607of nearly offsetting quantities resulting in loss of significance. Knuth
1608provides two instructive examples where rounded floating point arithmetic with
1609insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001610properties of addition:
1611
1612.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001613
1614 # Examples from Seminumerical Algorithms, Section 4.2.2.
1615 >>> from decimal import Decimal, getcontext
1616 >>> getcontext().prec = 8
1617
1618 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1619 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001620 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001621 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001622 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001623
1624 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1625 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001626 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001627 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001628 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001629
1630The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001631expanding the precision sufficiently to avoid loss of significance:
1632
1633.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001634
1635 >>> getcontext().prec = 20
1636 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1637 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001638 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001639 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001640 Decimal('9.51111111')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001641 >>>
Georg Brandl8ec7f652007-08-15 14:28:01 +00001642 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1643 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001644 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001645 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001646 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001647
1648
1649Special values
1650^^^^^^^^^^^^^^
1651
1652The number system for the :mod:`decimal` module provides special values
1653including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001654and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001655
1656Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1657they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1658not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1659can result from rounding beyond the limits of the largest representable number.
1660
1661The infinities are signed (affine) and can be used in arithmetic operations
1662where they get treated as very large, indeterminate numbers. For instance,
1663adding a constant to infinity gives another infinite result.
1664
1665Some operations are indeterminate and return :const:`NaN`, or if the
1666:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1667``0/0`` returns :const:`NaN` which means "not a number". This variety of
1668:const:`NaN` is quiet and, once created, will flow through other computations
1669always resulting in another :const:`NaN`. This behavior can be useful for a
1670series of computations that occasionally have missing inputs --- it allows the
1671calculation to proceed while flagging specific results as invalid.
1672
1673A variant is :const:`sNaN` which signals rather than remaining quiet after every
1674operation. This is a useful return value when an invalid result needs to
1675interrupt a calculation for special handling.
1676
Mark Dickinson2fc92632008-02-06 22:10:50 +00001677The behavior of Python's comparison operators can be a little surprising where a
1678:const:`NaN` is involved. A test for equality where one of the operands is a
1679quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1680``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001681:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001682``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1683if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001684not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001685specify the behavior of direct comparisons; these rules for comparisons
1686involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1687section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001688and :meth:`compare-signal` methods instead.
1689
Georg Brandl8ec7f652007-08-15 14:28:01 +00001690The signed zeros can result from calculations that underflow. They keep the sign
1691that would have resulted if the calculation had been carried out to greater
1692precision. Since their magnitude is zero, both positive and negative zeros are
1693treated as equal and their sign is informational.
1694
1695In addition to the two signed zeros which are distinct yet equal, there are
1696various representations of zero with differing precisions yet equivalent in
1697value. This takes a bit of getting used to. For an eye accustomed to
1698normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001699the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001700
1701 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001702 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001703
Georg Brandlb19be572007-12-29 10:57:00 +00001704.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001705
1706
1707.. _decimal-threads:
1708
1709Working with threads
1710--------------------
1711
1712The :func:`getcontext` function accesses a different :class:`Context` object for
1713each thread. Having separate thread contexts means that threads may make
1714changes (such as ``getcontext.prec=10``) without interfering with other threads.
1715
1716Likewise, the :func:`setcontext` function automatically assigns its target to
1717the current thread.
1718
1719If :func:`setcontext` has not been called before :func:`getcontext`, then
1720:func:`getcontext` will automatically create a new context for use in the
1721current thread.
1722
1723The new context is copied from a prototype context called *DefaultContext*. To
1724control the defaults so that each thread will use the same values throughout the
1725application, directly modify the *DefaultContext* object. This should be done
1726*before* any threads are started so that there won't be a race condition between
1727threads calling :func:`getcontext`. For example::
1728
1729 # Set applicationwide defaults for all threads about to be launched
1730 DefaultContext.prec = 12
1731 DefaultContext.rounding = ROUND_DOWN
1732 DefaultContext.traps = ExtendedContext.traps.copy()
1733 DefaultContext.traps[InvalidOperation] = 1
1734 setcontext(DefaultContext)
1735
1736 # Afterwards, the threads can be started
1737 t1.start()
1738 t2.start()
1739 t3.start()
1740 . . .
1741
Georg Brandlb19be572007-12-29 10:57:00 +00001742.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001743
1744
1745.. _decimal-recipes:
1746
1747Recipes
1748-------
1749
1750Here are a few recipes that serve as utility functions and that demonstrate ways
1751to work with the :class:`Decimal` class::
1752
1753 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1754 pos='', neg='-', trailneg=''):
1755 """Convert Decimal to a money formatted string.
1756
1757 places: required number of places after the decimal point
1758 curr: optional currency symbol before the sign (may be blank)
1759 sep: optional grouping separator (comma, period, space, or blank)
1760 dp: decimal point indicator (comma or period)
1761 only specify as blank when places is zero
1762 pos: optional sign for positive numbers: '+', space or blank
1763 neg: optional sign for negative numbers: '-', '(', space or blank
1764 trailneg:optional trailing minus indicator: '-', ')', space or blank
1765
1766 >>> d = Decimal('-1234567.8901')
1767 >>> moneyfmt(d, curr='$')
1768 '-$1,234,567.89'
1769 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1770 '1.234.568-'
1771 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1772 '($1,234,567.89)'
1773 >>> moneyfmt(Decimal(123456789), sep=' ')
1774 '123 456 789.00'
1775 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001776 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001777
1778 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001779 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001780 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001781 result = []
1782 digits = map(str, digits)
1783 build, next = result.append, digits.pop
1784 if sign:
1785 build(trailneg)
1786 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001787 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001788 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001789 if not digits:
1790 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001791 i = 0
1792 while digits:
1793 build(next())
1794 i += 1
1795 if i == 3 and digits:
1796 i = 0
1797 build(sep)
1798 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001799 build(neg if sign else pos)
1800 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001801
1802 def pi():
1803 """Compute Pi to the current precision.
1804
1805 >>> print pi()
1806 3.141592653589793238462643383
1807
1808 """
1809 getcontext().prec += 2 # extra digits for intermediate steps
1810 three = Decimal(3) # substitute "three=3.0" for regular floats
1811 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1812 while s != lasts:
1813 lasts = s
1814 n, na = n+na, na+8
1815 d, da = d+da, da+32
1816 t = (t * n) / d
1817 s += t
1818 getcontext().prec -= 2
1819 return +s # unary plus applies the new precision
1820
1821 def exp(x):
1822 """Return e raised to the power of x. Result type matches input type.
1823
1824 >>> print exp(Decimal(1))
1825 2.718281828459045235360287471
1826 >>> print exp(Decimal(2))
1827 7.389056098930650227230427461
1828 >>> print exp(2.0)
1829 7.38905609893
1830 >>> print exp(2+0j)
1831 (7.38905609893+0j)
1832
1833 """
1834 getcontext().prec += 2
1835 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1836 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001837 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001838 i += 1
1839 fact *= i
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001840 num *= x
1841 s += num / fact
1842 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001843 return +s
1844
1845 def cos(x):
1846 """Return the cosine of x as measured in radians.
1847
1848 >>> print cos(Decimal('0.5'))
1849 0.8775825618903727161162815826
1850 >>> print cos(0.5)
1851 0.87758256189
1852 >>> print cos(0.5+0j)
1853 (0.87758256189+0j)
1854
1855 """
1856 getcontext().prec += 2
1857 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1858 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001859 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001860 i += 2
1861 fact *= i * (i-1)
1862 num *= x * x
1863 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001864 s += num / fact * sign
1865 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001866 return +s
1867
1868 def sin(x):
1869 """Return the sine of x as measured in radians.
1870
1871 >>> print sin(Decimal('0.5'))
1872 0.4794255386042030002732879352
1873 >>> print sin(0.5)
1874 0.479425538604
1875 >>> print sin(0.5+0j)
1876 (0.479425538604+0j)
1877
1878 """
1879 getcontext().prec += 2
1880 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1881 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001882 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001883 i += 2
1884 fact *= i * (i-1)
1885 num *= x * x
1886 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001887 s += num / fact * sign
1888 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001889 return +s
1890
1891
Georg Brandlb19be572007-12-29 10:57:00 +00001892.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001893
1894
1895.. _decimal-faq:
1896
1897Decimal FAQ
1898-----------
1899
1900Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1901minimize typing when using the interactive interpreter?
1902
Georg Brandl9f662322008-03-22 11:47:10 +00001903A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001904
1905 >>> D = decimal.Decimal
1906 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001907 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001908
1909Q. In a fixed-point application with two decimal places, some inputs have many
1910places and need to be rounded. Others are not supposed to have excess digits
1911and need to be validated. What methods should be used?
1912
1913A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001914the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001915
1916 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1917
1918 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001919 >>> Decimal('3.214').quantize(TWOPLACES)
1920 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001921
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001922 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001923 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1924 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001925
Raymond Hettingerabe32372008-02-14 02:41:22 +00001926 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001927 Traceback (most recent call last):
1928 ...
Georg Brandlf6dab952009-04-28 21:48:35 +00001929 Inexact: None
Georg Brandl8ec7f652007-08-15 14:28:01 +00001930
1931Q. Once I have valid two place inputs, how do I maintain that invariant
1932throughout an application?
1933
Raymond Hettinger46314812008-02-14 10:46:57 +00001934A. Some operations like addition, subtraction, and multiplication by an integer
1935will automatically preserve fixed point. Others operations, like division and
1936non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001937be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001938
1939 >>> a = Decimal('102.72') # Initial fixed-point values
1940 >>> b = Decimal('3.17')
1941 >>> a + b # Addition preserves fixed-point
1942 Decimal('105.89')
1943 >>> a - b
1944 Decimal('99.55')
1945 >>> a * 42 # So does integer multiplication
1946 Decimal('4314.24')
1947 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1948 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001949 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001950 Decimal('0.03')
1951
1952In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001953to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001954
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001955 >>> def mul(x, y, fp=TWOPLACES):
1956 ... return (x * y).quantize(fp)
1957 >>> def div(x, y, fp=TWOPLACES):
1958 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001959
Raymond Hettinger46314812008-02-14 10:46:57 +00001960 >>> mul(a, b) # Automatically preserve fixed-point
1961 Decimal('325.62')
1962 >>> div(b, a)
1963 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001964
1965Q. There are many ways to express the same value. The numbers :const:`200`,
1966:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1967various precisions. Is there a way to transform them to a single recognizable
1968canonical value?
1969
1970A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001971representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001972
1973 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1974 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001975 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001976
1977Q. Some decimal values always print with exponential notation. Is there a way
1978to get a non-exponential representation?
1979
1980A. For some values, exponential notation is the only way to express the number
1981of significant places in the coefficient. For example, expressing
1982:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1983original's two-place significance.
1984
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001985If an application does not care about tracking significance, it is easy to
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001986remove the exponent and trailing zeros, losing significance, but keeping the
1987value unchanged::
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001988
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001989 def remove_exponent(d):
1990 '''Remove exponent and trailing zeros.
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001991
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001992 >>> remove_exponent(Decimal('5E+3'))
1993 Decimal('5000')
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001994
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001995 '''
1996 return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001997
Raymond Hettingered171ab2010-04-02 18:39:24 +00001998Q. Is there a way to convert a regular float to a :class:`Decimal`?
Georg Brandl9f662322008-03-22 11:47:10 +00001999
Mark Dickinsonb1affc52010-04-04 22:09:21 +00002000A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettingered171ab2010-04-02 18:39:24 +00002001Decimal though an exact conversion may take more precision than intuition would
2002suggest:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002003
Raymond Hettingered171ab2010-04-02 18:39:24 +00002004.. doctest::
Georg Brandl8ec7f652007-08-15 14:28:01 +00002005
Raymond Hettingered171ab2010-04-02 18:39:24 +00002006 >>> Decimal(math.pi)
2007 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002008
2009Q. Within a complex calculation, how can I make sure that I haven't gotten a
2010spurious result because of insufficient precision or rounding anomalies.
2011
2012A. The decimal module makes it easy to test results. A best practice is to
2013re-run calculations using greater precision and with various rounding modes.
2014Widely differing results indicate insufficient precision, rounding mode issues,
2015ill-conditioned inputs, or a numerically unstable algorithm.
2016
2017Q. I noticed that context precision is applied to the results of operations but
2018not to the inputs. Is there anything to watch out for when mixing values of
2019different precisions?
2020
2021A. Yes. The principle is that all values are considered to be exact and so is
2022the arithmetic on those values. Only the results are rounded. The advantage
2023for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00002024results can look odd if you forget that the inputs haven't been rounded:
2025
2026.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00002027
2028 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00002029 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002030 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00002031 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002032 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002033
2034The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00002035using the unary plus operation:
2036
2037.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00002038
2039 >>> getcontext().prec = 3
2040 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00002041 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002042
2043Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00002044:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002045
2046 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002047 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002048