blob: 564d10c5f7d70a2176a6440e22fd2612545aaf29 [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
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000114 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Mark Dickinsonff6672f2008-02-07 01:14:23 +0000115 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116
Georg Brandlb19be572007-12-29 10:57:00 +0000117.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118
119
120.. _decimal-tutorial:
121
122Quick-start Tutorial
123--------------------
124
125The usual start to using decimals is importing the module, viewing the current
126context with :func:`getcontext` and, if necessary, setting new values for
Georg Brandl9f662322008-03-22 11:47:10 +0000127precision, rounding, or enabled traps::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
129 >>> from decimal import *
130 >>> getcontext()
131 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000132 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
133 InvalidOperation])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134
135 >>> getcontext().prec = 7 # Set a new precision
136
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000137Decimal instances can be constructed from integers, strings, floats, or tuples.
138Construction from an integer or a float performs an exact conversion of the
139value of that integer or float. Decimal numbers include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000140:const:`NaN` which stands for "Not a number", positive and negative
Georg Brandl17baef02008-03-22 10:56:23 +0000141:const:`Infinity`, and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000143 >>> getcontext().prec = 28
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000145 Decimal('10')
146 >>> Decimal('3.14')
147 Decimal('3.14')
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000148 >>> Decimal(3.14)
149 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000151 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000153 Decimal('1.41421356237')
154 >>> Decimal(2) ** Decimal('0.5')
155 Decimal('1.414213562373095048801688724')
156 >>> Decimal('NaN')
157 Decimal('NaN')
158 >>> Decimal('-Infinity')
159 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
161The significance of a new Decimal is determined solely by the number of digits
162input. Context precision and rounding only come into play during arithmetic
Georg Brandl17baef02008-03-22 10:56:23 +0000163operations.
164
165.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166
167 >>> getcontext().prec = 6
168 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000169 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000170 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000171 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000173 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174 >>> getcontext().rounding = ROUND_UP
175 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000176 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
178Decimals interact well with much of the rest of Python. Here is a small decimal
Georg Brandl9f662322008-03-22 11:47:10 +0000179floating point flying circus:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000180
Georg Brandl838b4b02008-03-22 13:07:06 +0000181.. doctest::
182 :options: +NORMALIZE_WHITESPACE
183
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
185 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000186 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000187 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000188 Decimal('0.03')
Georg Brandl838b4b02008-03-22 13:07:06 +0000189 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000190 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
191 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000192 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000193 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194 >>> a,b,c = data[:3]
195 >>> str(a)
196 '1.34'
197 >>> float(a)
Mark Dickinson6b87f112009-11-24 14:27:02 +0000198 1.34
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199 >>> round(a, 1) # round() first converts to binary floating point
200 1.3
201 >>> int(a)
202 1
203 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000204 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000206 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000207 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000208 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209
Georg Brandl9f662322008-03-22 11:47:10 +0000210And some mathematical functions are also available to Decimal:
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000211
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000212 >>> getcontext().prec = 28
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000213 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000214 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000215 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000216 Decimal('2.718281828459045235360287471')
217 >>> Decimal('10').ln()
218 Decimal('2.302585092994045684017991455')
219 >>> Decimal('10').log10()
220 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000221
Georg Brandl8ec7f652007-08-15 14:28:01 +0000222The :meth:`quantize` method rounds a number to a fixed exponent. This method is
223useful for monetary applications that often round results to a fixed number of
Georg Brandl9f662322008-03-22 11:47:10 +0000224places:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
226 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000227 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000229 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000230
231As shown above, the :func:`getcontext` function accesses the current context and
232allows the settings to be changed. This approach meets the needs of most
233applications.
234
235For more advanced work, it may be useful to create alternate contexts using the
236Context() constructor. To make an alternate active, use the :func:`setcontext`
237function.
238
Serhiy Storchaka251aede2015-03-14 21:32:41 +0200239In accordance with the standard, the :mod:`decimal` module provides two ready to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
241former is especially useful for debugging because many of the traps are
Georg Brandl9f662322008-03-22 11:47:10 +0000242enabled:
243
244.. doctest:: newcontext
245 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
247 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
248 >>> setcontext(myothercontext)
249 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000250 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251
252 >>> ExtendedContext
253 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
254 capitals=1, flags=[], traps=[])
255 >>> setcontext(ExtendedContext)
256 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000257 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000258 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000259 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000260
261 >>> setcontext(BasicContext)
262 >>> Decimal(42) / Decimal(0)
263 Traceback (most recent call last):
264 File "<pyshell#143>", line 1, in -toplevel-
265 Decimal(42) / Decimal(0)
266 DivisionByZero: x / 0
267
268Contexts also have signal flags for monitoring exceptional conditions
269encountered during computations. The flags remain set until explicitly cleared,
270so it is best to clear the flags before each set of monitored computations by
271using the :meth:`clear_flags` method. ::
272
273 >>> setcontext(ExtendedContext)
274 >>> getcontext().clear_flags()
275 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000276 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277 >>> getcontext()
278 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000279 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280
281The *flags* entry shows that the rational approximation to :const:`Pi` was
282rounded (digits beyond the context precision were thrown away) and that the
283result is inexact (some of the discarded digits were non-zero).
284
285Individual traps are set using the dictionary in the :attr:`traps` field of a
Georg Brandl9f662322008-03-22 11:47:10 +0000286context:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
Georg Brandl9f662322008-03-22 11:47:10 +0000288.. doctest:: newcontext
289
290 >>> setcontext(ExtendedContext)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000292 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000293 >>> getcontext().traps[DivisionByZero] = 1
294 >>> Decimal(1) / Decimal(0)
295 Traceback (most recent call last):
296 File "<pyshell#112>", line 1, in -toplevel-
297 Decimal(1) / Decimal(0)
298 DivisionByZero: x / 0
299
300Most programs adjust the current context only once, at the beginning of the
301program. And, in many applications, data is converted to :class:`Decimal` with
302a single cast inside a loop. With context set and decimals created, the bulk of
303the program manipulates the data no differently than with other Python numeric
304types.
305
Georg Brandlb19be572007-12-29 10:57:00 +0000306.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
308
309.. _decimal-decimal:
310
311Decimal objects
312---------------
313
314
315.. class:: Decimal([value [, context]])
316
Georg Brandlb19be572007-12-29 10:57:00 +0000317 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318
Raymond Hettingered171ab2010-04-02 18:39:24 +0000319 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000320 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000321 string, it should conform to the decimal numeric string syntax after leading
322 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000323
324 sign ::= '+' | '-'
325 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
326 indicator ::= 'e' | 'E'
327 digits ::= digit [digit]...
328 decimal-part ::= digits '.' [digits] | ['.'] digits
329 exponent-part ::= indicator [sign] digits
330 infinity ::= 'Infinity' | 'Inf'
331 nan ::= 'NaN' [digits] | 'sNaN' [digits]
332 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000333 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334
Mark Dickinson4326ad82009-08-02 10:59:36 +0000335 If *value* is a unicode string then other Unicode decimal digits
336 are also permitted where ``digit`` appears above. These include
337 decimal digits from various other alphabets (for example,
338 Arabic-Indic and Devanāgarī digits) along with the fullwidth digits
339 ``u'\uff10'`` through ``u'\uff19'``.
340
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341 If *value* is a :class:`tuple`, it should have three components, a sign
342 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
343 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000344 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000345
Raymond Hettingered171ab2010-04-02 18:39:24 +0000346 If *value* is a :class:`float`, the binary floating point value is losslessly
347 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000348 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
349 converts to
350 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettingered171ab2010-04-02 18:39:24 +0000351
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352 The *context* precision does not affect how many digits are stored. That is
353 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000354 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000355 only three.
356
357 The purpose of the *context* argument is determining what to do if *value* is a
358 malformed string. If the context traps :const:`InvalidOperation`, an exception
359 is raised; otherwise, the constructor returns a new Decimal with the value of
360 :const:`NaN`.
361
362 Once constructed, :class:`Decimal` objects are immutable.
363
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000364 .. versionchanged:: 2.6
365 leading and trailing whitespace characters are permitted when
366 creating a Decimal instance from a string.
367
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000368 .. versionchanged:: 2.7
Ezio Melotti6f65d2d2010-04-04 23:21:53 +0000369 The argument to the constructor is now permitted to be a :class:`float` instance.
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000370
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000371 Decimal floating point objects share many properties with the other built-in
372 numeric types such as :class:`float` and :class:`int`. All of the usual math
373 operations and special methods apply. Likewise, decimal objects can be
374 copied, pickled, printed, used as dictionary keys, used as set elements,
375 compared, sorted, and coerced to another type (such as :class:`float` or
376 :class:`long`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000377
Mark Dickinson0d187312012-11-18 10:20:28 +0000378 There are some small differences between arithmetic on Decimal objects and
379 arithmetic on integers and floats. When the remainder operator ``%`` is
380 applied to Decimal objects, the sign of the result is the sign of the
381 *dividend* rather than the sign of the divisor::
382
383 >>> (-7) % 4
384 1
385 >>> Decimal(-7) % Decimal(4)
386 Decimal('-3')
387
388 The integer division operator ``//`` behaves analogously, returning the
389 integer part of the true quotient (truncating towards zero) rather than its
Mark Dickinson3c9181b2012-11-18 10:41:29 +0000390 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::
Mark Dickinson0d187312012-11-18 10:20:28 +0000391
392 >>> -7 // 4
393 -2
394 >>> Decimal(-7) // Decimal(4)
395 Decimal('-1')
396
397 The ``%`` and ``//`` operators implement the ``remainder`` and
398 ``divide-integer`` operations (respectively) as described in the
399 specification.
400
Mark Dickinson99d80962010-04-02 08:53:22 +0000401 Decimal objects cannot generally be combined with floats in
402 arithmetic operations: an attempt to add a :class:`Decimal` to a
403 :class:`float`, for example, will raise a :exc:`TypeError`.
404 There's one exception to this rule: it's possible to use Python's
405 comparison operators to compare a :class:`float` instance ``x``
406 with a :class:`Decimal` instance ``y``. Without this exception,
407 comparisons between :class:`Decimal` and :class:`float` instances
408 would follow the general rules for comparing objects of different
409 types described in the :ref:`expressions` section of the reference
410 manual, leading to confusing results.
411
412 .. versionchanged:: 2.7
413 A comparison between a :class:`float` instance ``x`` and a
414 :class:`Decimal` instance ``y`` now returns a result based on
415 the values of ``x`` and ``y``. In earlier versions ``x < y``
416 returned the same (arbitrary) result for any :class:`Decimal`
417 instance ``x`` and any :class:`float` instance ``y``.
418
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000419 In addition to the standard numeric properties, decimal floating point
420 objects also have a number of specialized methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000421
422
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000423 .. method:: adjusted()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000425 Return the adjusted exponent after shifting out the coefficient's
426 rightmost digits until only the lead digit remains:
427 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
428 position of the most significant digit with respect to the decimal point.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
430
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000431 .. method:: as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000432
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000433 Return a :term:`named tuple` representation of the number:
434 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandle3c3db52008-01-11 09:55:53 +0000435
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000436 .. versionchanged:: 2.6
437 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438
439
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000440 .. method:: canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000441
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000442 Return the canonical encoding of the argument. Currently, the encoding of
443 a :class:`Decimal` instance is always canonical, so this operation returns
444 its argument unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000445
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000446 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000447
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000448 .. method:: compare(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000449
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000450 Compare the values of two Decimal instances. This operation behaves in
451 the same way as the usual comparison method :meth:`__cmp__`, except that
452 :meth:`compare` returns a Decimal instance rather than an integer, and if
453 either operand is a NaN then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000454
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000455 a or b is a NaN ==> Decimal('NaN')
456 a < b ==> Decimal('-1')
457 a == b ==> Decimal('0')
458 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000460 .. method:: compare_signal(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000461
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000462 This operation is identical to the :meth:`compare` method, except that all
463 NaNs signal. That is, if neither operand is a signaling NaN then any
464 quiet NaN operand is treated as though it were a signaling NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000465
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000466 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000467
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000468 .. method:: compare_total(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000469
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000470 Compare two operands using their abstract representation rather than their
471 numerical value. Similar to the :meth:`compare` method, but the result
472 gives a total ordering on :class:`Decimal` instances. Two
473 :class:`Decimal` instances with the same numeric value but different
474 representations compare unequal in this ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000475
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000476 >>> Decimal('12.0').compare_total(Decimal('12'))
477 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000478
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000479 Quiet and signaling NaNs are also included in the total ordering. The
480 result of this function is ``Decimal('0')`` if both operands have the same
481 representation, ``Decimal('-1')`` if the first operand is lower in the
482 total order than the second, and ``Decimal('1')`` if the first operand is
483 higher in the total order than the second operand. See the specification
484 for details of the total order.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000485
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000486 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000487
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000488 .. method:: compare_total_mag(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000489
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000490 Compare two operands using their abstract representation rather than their
491 value as in :meth:`compare_total`, but ignoring the sign of each operand.
492 ``x.compare_total_mag(y)`` is equivalent to
493 ``x.copy_abs().compare_total(y.copy_abs())``.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000494
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000495 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000496
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000497 .. method:: conjugate()
498
499 Just returns self, this method is only to comply with the Decimal
500 Specification.
501
502 .. versionadded:: 2.6
503
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000504 .. method:: copy_abs()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000505
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000506 Return the absolute value of the argument. This operation is unaffected
507 by the context and is quiet: no flags are changed and no rounding is
508 performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000509
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000510 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000511
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000512 .. method:: copy_negate()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000513
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000514 Return the negation of the argument. This operation is unaffected by the
515 context and is quiet: no flags are changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000516
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000517 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000518
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000519 .. method:: copy_sign(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000520
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000521 Return a copy of the first operand with the sign set to be the same as the
522 sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000523
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000524 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
525 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000526
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000527 This operation is unaffected by the context and is quiet: no flags are
528 changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000529
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000530 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000531
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000532 .. method:: exp([context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000533
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000534 Return the value of the (natural) exponential function ``e**x`` at the
535 given number. The result is correctly rounded using the
536 :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000537
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000538 >>> Decimal(1).exp()
539 Decimal('2.718281828459045235360287471')
540 >>> Decimal(321).exp()
541 Decimal('2.561702493119680037517373933E+139')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000542
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000543 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000544
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000545 .. method:: from_float(f)
546
547 Classmethod that converts a float to a decimal number, exactly.
548
549 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
550 Since 0.1 is not exactly representable in binary floating point, the
551 value is stored as the nearest representable value which is
552 `0x1.999999999999ap-4`. That equivalent value in decimal is
553 `0.1000000000000000055511151231257827021181583404541015625`.
554
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000555 .. note:: From Python 2.7 onwards, a :class:`Decimal` instance
556 can also be constructed directly from a :class:`float`.
557
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000558 .. doctest::
559
560 >>> Decimal.from_float(0.1)
561 Decimal('0.1000000000000000055511151231257827021181583404541015625')
562 >>> Decimal.from_float(float('nan'))
563 Decimal('NaN')
564 >>> Decimal.from_float(float('inf'))
565 Decimal('Infinity')
566 >>> Decimal.from_float(float('-inf'))
567 Decimal('-Infinity')
568
569 .. versionadded:: 2.7
570
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000571 .. method:: fma(other, third[, context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000572
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000573 Fused multiply-add. Return self*other+third with no rounding of the
574 intermediate product self*other.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000575
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000576 >>> Decimal(2).fma(3, 5)
577 Decimal('11')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000578
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000579 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000580
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000581 .. method:: is_canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000582
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000583 Return :const:`True` if the argument is canonical and :const:`False`
584 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
585 this operation always returns :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000586
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000587 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000588
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000589 .. method:: is_finite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000590
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000591 Return :const:`True` if the argument is a finite number, and
592 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000593
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000594 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000595
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000596 .. method:: is_infinite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000597
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000598 Return :const:`True` if the argument is either positive or negative
599 infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000600
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000601 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000602
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000603 .. method:: is_nan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000604
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000605 Return :const:`True` if the argument is a (quiet or signaling) NaN and
606 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000607
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000608 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000609
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000610 .. method:: is_normal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000611
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000612 Return :const:`True` if the argument is a *normal* finite non-zero
613 number with an adjusted exponent greater than or equal to *Emin*.
614 Return :const:`False` if the argument is zero, subnormal, infinite or a
615 NaN. Note, the term *normal* is used here in a different sense with
616 the :meth:`normalize` method which is used to create canonical values.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000617
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000618 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000619
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000620 .. method:: is_qnan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000621
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000622 Return :const:`True` if the argument is a quiet NaN, and
623 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000624
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000625 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000626
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000627 .. method:: is_signed()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000628
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000629 Return :const:`True` if the argument has a negative sign and
630 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000631
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000632 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000633
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000634 .. method:: is_snan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000635
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000636 Return :const:`True` if the argument is a signaling NaN and :const:`False`
637 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000638
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000639 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000640
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000641 .. method:: is_subnormal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000642
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000643 Return :const:`True` if the argument is subnormal, and :const:`False`
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000644 otherwise. A number is subnormal is if it is nonzero, finite, and has an
645 adjusted exponent less than *Emin*.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000646
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000647 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000648
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000649 .. method:: is_zero()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000650
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000651 Return :const:`True` if the argument is a (positive or negative) zero and
652 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000653
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000654 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000655
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000656 .. method:: ln([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000657
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000658 Return the natural (base e) logarithm of the operand. The result is
659 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000660
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000661 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000662
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000663 .. method:: log10([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000664
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000665 Return the base ten logarithm of the operand. The result is correctly
666 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000667
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000668 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000669
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000670 .. method:: logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000671
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000672 For a nonzero number, return the adjusted exponent of its operand as a
673 :class:`Decimal` instance. If the operand is a zero then
674 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
675 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
676 returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000677
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000678 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000679
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000680 .. method:: logical_and(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000681
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000682 :meth:`logical_and` is a logical operation which takes two *logical
683 operands* (see :ref:`logical_operands_label`). The result is the
684 digit-wise ``and`` of the two operands.
685
686 .. versionadded:: 2.6
687
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000688 .. method:: logical_invert([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000689
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000690 :meth:`logical_invert` is a logical operation. The
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000691 result is the digit-wise inversion of the operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000692
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000693 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000694
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000695 .. method:: logical_or(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000696
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000697 :meth:`logical_or` is a logical operation which takes two *logical
698 operands* (see :ref:`logical_operands_label`). The result is the
699 digit-wise ``or`` of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000700
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000701 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000702
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000703 .. method:: logical_xor(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000704
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000705 :meth:`logical_xor` is a logical operation which takes two *logical
706 operands* (see :ref:`logical_operands_label`). The result is the
707 digit-wise exclusive or of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000708
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000709 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000710
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000711 .. method:: max(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000712
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000713 Like ``max(self, other)`` except that the context rounding rule is applied
714 before returning and that :const:`NaN` values are either signaled or
715 ignored (depending on the context and whether they are signaling or
716 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000717
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000718 .. method:: max_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000719
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000720 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000721 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000722
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000723 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000724
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000725 .. method:: min(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000727 Like ``min(self, other)`` except that the context rounding rule is applied
728 before returning and that :const:`NaN` values are either signaled or
729 ignored (depending on the context and whether they are signaling or
730 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000731
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000732 .. method:: min_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000733
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000734 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000735 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000736
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000737 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000738
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000739 .. method:: next_minus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000740
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000741 Return the largest number representable in the given context (or in the
742 current thread's context if no context is given) that is smaller than the
743 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000744
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000745 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000746
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000747 .. method:: next_plus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000748
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000749 Return the smallest number representable in the given context (or in the
750 current thread's context if no context is given) that is larger than the
751 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000752
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000753 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000754
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000755 .. method:: next_toward(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000756
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000757 If the two operands are unequal, return the number closest to the first
758 operand in the direction of the second operand. If both operands are
759 numerically equal, return a copy of the first operand with the sign set to
760 be the same as the sign of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000761
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000762 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000763
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000764 .. method:: normalize([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000765
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000766 Normalize the number by stripping the rightmost trailing zeros and
767 converting any result equal to :const:`Decimal('0')` to
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700768 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000769 of an equivalence class. For example, ``Decimal('32.100')`` and
770 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
771 ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000772
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000773 .. method:: number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000774
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000775 Return a string describing the *class* of the operand. The returned value
776 is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000777
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000778 * ``"-Infinity"``, indicating that the operand is negative infinity.
779 * ``"-Normal"``, indicating that the operand is a negative normal number.
780 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
781 * ``"-Zero"``, indicating that the operand is a negative zero.
782 * ``"+Zero"``, indicating that the operand is a positive zero.
783 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
784 * ``"+Normal"``, indicating that the operand is a positive normal number.
785 * ``"+Infinity"``, indicating that the operand is positive infinity.
786 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
787 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000788
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000789 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000790
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000791 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000792
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000793 Return a value equal to the first operand after rounding and having the
794 exponent of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000795
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000796 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
797 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000798
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000799 Unlike other operations, if the length of the coefficient after the
800 quantize operation would be greater than precision, then an
801 :const:`InvalidOperation` is signaled. This guarantees that, unless there
802 is an error condition, the quantized exponent is always equal to that of
803 the right-hand operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000804
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000805 Also unlike other operations, quantize never signals Underflow, even if
806 the result is subnormal and inexact.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000807
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000808 If the exponent of the second operand is larger than that of the first
809 then rounding may be necessary. In this case, the rounding mode is
810 determined by the ``rounding`` argument if given, else by the given
811 ``context`` argument; if neither argument is given the rounding mode of
812 the current thread's context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000813
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000814 If *watchexp* is set (default), then an error is returned whenever the
815 resulting exponent is greater than :attr:`Emax` or less than
816 :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000817
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000818 .. method:: radix()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000819
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000820 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
821 class does all its arithmetic. Included for compatibility with the
822 specification.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000823
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000824 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000826 .. method:: remainder_near(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000827
Mark Dickinson89e8f542012-10-31 19:44:09 +0000828 Return the remainder from dividing *self* by *other*. This differs from
829 ``self % other`` in that the sign of the remainder is chosen so as to
830 minimize its absolute value. More precisely, the return value is
831 ``self - n * other`` where ``n`` is the integer nearest to the exact
832 value of ``self / other``, and if two integers are equally near then the
833 even one is chosen.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834
Mark Dickinson89e8f542012-10-31 19:44:09 +0000835 If the result is zero then its sign will be the sign of *self*.
836
837 >>> Decimal(18).remainder_near(Decimal(10))
838 Decimal('-2')
839 >>> Decimal(25).remainder_near(Decimal(10))
840 Decimal('5')
841 >>> Decimal(35).remainder_near(Decimal(10))
842 Decimal('-5')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000843
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000844 .. method:: rotate(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000845
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000846 Return the result of rotating the digits of the first operand by an amount
847 specified by the second operand. The second operand must be an integer in
848 the range -precision through precision. The absolute value of the second
849 operand gives the number of places to rotate. If the second operand is
850 positive then rotation is to the left; otherwise rotation is to the right.
851 The coefficient of the first operand is padded on the left with zeros to
852 length precision if necessary. The sign and exponent of the first operand
853 are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000854
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000855 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000856
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000857 .. method:: same_quantum(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000858
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000859 Test whether self and other have the same exponent or whether both are
860 :const:`NaN`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000861
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000862 .. method:: scaleb(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000863
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000864 Return the first operand with exponent adjusted by the second.
865 Equivalently, return the first operand multiplied by ``10**other``. The
866 second operand must be an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000867
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000868 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000869
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000870 .. method:: shift(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000871
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000872 Return the result of shifting the digits of the first operand by an amount
873 specified by the second operand. The second operand must be an integer in
874 the range -precision through precision. The absolute value of the second
875 operand gives the number of places to shift. If the second operand is
876 positive then the shift is to the left; otherwise the shift is to the
877 right. Digits shifted into the coefficient are zeros. The sign and
878 exponent of the first operand are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000879
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000880 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000881
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000882 .. method:: sqrt([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000884 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000885
886
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000887 .. method:: to_eng_string([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000888
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000889 Convert to an engineering-type string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000890
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000891 Engineering notation has an exponent which is a multiple of 3, so there
892 are up to 3 digits left of the decimal place. For example, converts
893 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000894
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000895 .. method:: to_integral([rounding[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000896
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000897 Identical to the :meth:`to_integral_value` method. The ``to_integral``
898 name has been kept for compatibility with older versions.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000899
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000900 .. method:: to_integral_exact([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000901
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000902 Round to the nearest integer, signaling :const:`Inexact` or
903 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
904 determined by the ``rounding`` parameter if given, else by the given
905 ``context``. If neither parameter is given then the rounding mode of the
906 current context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000907
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000908 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000909
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000910 .. method:: to_integral_value([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000911
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000912 Round to the nearest integer without signaling :const:`Inexact` or
913 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
914 rounding method in either the supplied *context* or the current context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000915
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000916 .. versionchanged:: 2.6
917 renamed from ``to_integral`` to ``to_integral_value``. The old name
918 remains valid for compatibility.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000919
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000920.. _logical_operands_label:
921
922Logical operands
923^^^^^^^^^^^^^^^^
924
925The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
926and :meth:`logical_xor` methods expect their arguments to be *logical
927operands*. A *logical operand* is a :class:`Decimal` instance whose
928exponent and sign are both zero, and whose digits are all either
929:const:`0` or :const:`1`.
930
Georg Brandlb19be572007-12-29 10:57:00 +0000931.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000932
933
934.. _decimal-context:
935
936Context objects
937---------------
938
939Contexts are environments for arithmetic operations. They govern precision, set
940rules for rounding, determine which signals are treated as exceptions, and limit
941the range for exponents.
942
943Each thread has its own current context which is accessed or changed using the
944:func:`getcontext` and :func:`setcontext` functions:
945
946
947.. function:: getcontext()
948
949 Return the current context for the active thread.
950
951
952.. function:: setcontext(c)
953
954 Set the current context for the active thread to *c*.
955
956Beginning with Python 2.5, you can also use the :keyword:`with` statement and
957the :func:`localcontext` function to temporarily change the active context.
958
959
960.. function:: localcontext([c])
961
962 Return a context manager that will set the current context for the active thread
963 to a copy of *c* on entry to the with-statement and restore the previous context
964 when exiting the with-statement. If no context is specified, a copy of the
965 current context is used.
966
967 .. versionadded:: 2.5
968
969 For example, the following code sets the current decimal precision to 42 places,
970 performs a calculation, and then automatically restores the previous context::
971
Georg Brandl8ec7f652007-08-15 14:28:01 +0000972 from decimal import localcontext
973
974 with localcontext() as ctx:
975 ctx.prec = 42 # Perform a high precision calculation
976 s = calculate_something()
977 s = +s # Round the final result back to the default precision
978
Raymond Hettinger56f5c382012-05-11 12:50:11 -0700979 with localcontext(BasicContext): # temporarily use the BasicContext
980 print Decimal(1) / Decimal(7)
981 print Decimal(355) / Decimal(113)
982
Georg Brandl8ec7f652007-08-15 14:28:01 +0000983New contexts can also be created using the :class:`Context` constructor
984described below. In addition, the module provides three pre-made contexts:
985
986
987.. class:: BasicContext
988
989 This is a standard context defined by the General Decimal Arithmetic
990 Specification. Precision is set to nine. Rounding is set to
991 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
992 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
993 :const:`Subnormal`.
994
995 Because many of the traps are enabled, this context is useful for debugging.
996
997
998.. class:: ExtendedContext
999
1000 This is a standard context defined by the General Decimal Arithmetic
1001 Specification. Precision is set to nine. Rounding is set to
1002 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
1003 exceptions are not raised during computations).
1004
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001005 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +00001006 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
1007 raising exceptions. This allows an application to complete a run in the
1008 presence of conditions that would otherwise halt the program.
1009
1010
1011.. class:: DefaultContext
1012
1013 This context is used by the :class:`Context` constructor as a prototype for new
1014 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Krah3d08d882010-05-29 12:54:35 +00001015 default for new contexts created by the :class:`Context` constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001016
1017 This context is most useful in multi-threaded environments. Changing one of the
1018 fields before threads are started has the effect of setting system-wide
1019 defaults. Changing the fields after threads have started is not recommended as
1020 it would require thread synchronization to prevent race conditions.
1021
1022 In single threaded environments, it is preferable to not use this context at
1023 all. Instead, simply create contexts explicitly as described below.
1024
1025 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
1026 for Overflow, InvalidOperation, and DivisionByZero.
1027
1028In addition to the three supplied contexts, new contexts can be created with the
1029:class:`Context` constructor.
1030
1031
1032.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
1033
1034 Creates a new context. If a field is not specified or is :const:`None`, the
1035 default values are copied from the :const:`DefaultContext`. If the *flags*
1036 field is not specified or is :const:`None`, all flags are cleared.
1037
1038 The *prec* field is a positive integer that sets the precision for arithmetic
1039 operations in the context.
1040
1041 The *rounding* option is one of:
1042
1043 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
1044 * :const:`ROUND_DOWN` (towards zero),
1045 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
1046 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
1047 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
1048 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
1049 * :const:`ROUND_UP` (away from zero).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001050 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001051 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001052
1053 The *traps* and *flags* fields list any signals to be set. Generally, new
1054 contexts should only set traps and leave the flags clear.
1055
1056 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
1057 for exponents.
1058
1059 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
1060 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
1061 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1062
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001063 .. versionchanged:: 2.6
1064 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001065
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001066 The :class:`Context` class defines several general purpose methods as well as
1067 a large number of methods for doing arithmetic directly in a given context.
1068 In addition, for each of the :class:`Decimal` methods described above (with
1069 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson6d8effb2010-02-18 14:27:02 +00001070 a corresponding :class:`Context` method. For example, for a :class:`Context`
1071 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1072 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
1073 Python integer (an instance of :class:`int` or :class:`long`) anywhere that a
1074 Decimal instance is accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075
1076
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001077 .. method:: clear_flags()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001078
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001079 Resets all of the flags to :const:`0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001080
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001081 .. method:: copy()
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001082
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001083 Return a duplicate of the context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001084
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001085 .. method:: copy_decimal(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001086
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001087 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001088
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001089 .. method:: create_decimal(num)
Georg Brandl9f662322008-03-22 11:47:10 +00001090
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001091 Creates a new Decimal instance from *num* but using *self* as
1092 context. Unlike the :class:`Decimal` constructor, the context precision,
1093 rounding method, flags, and traps are applied to the conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001094
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001095 This is useful because constants are often given to a greater precision
1096 than is needed by the application. Another benefit is that rounding
1097 immediately eliminates unintended effects from digits beyond the current
1098 precision. In the following example, using unrounded inputs means that
1099 adding zero to a sum can change the result:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001100
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001101 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001102
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001103 >>> getcontext().prec = 3
1104 >>> Decimal('3.4445') + Decimal('1.0023')
1105 Decimal('4.45')
1106 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1107 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001109 This method implements the to-number operation of the IBM specification.
1110 If the argument is a string, no leading or trailing whitespace is
1111 permitted.
1112
Georg Brandlaa5bb322009-01-03 19:44:48 +00001113 .. method:: create_decimal_from_float(f)
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001114
1115 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandla24067e2009-01-03 20:15:14 +00001116 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001117 the context precision, rounding method, flags, and traps are applied to
1118 the conversion.
1119
1120 .. doctest::
1121
Georg Brandlaa5bb322009-01-03 19:44:48 +00001122 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1123 >>> context.create_decimal_from_float(math.pi)
1124 Decimal('3.1415')
1125 >>> context = Context(prec=5, traps=[Inexact])
1126 >>> context.create_decimal_from_float(math.pi)
1127 Traceback (most recent call last):
1128 ...
1129 Inexact: None
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001130
1131 .. versionadded:: 2.7
1132
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001133 .. method:: Etiny()
1134
1135 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1136 value for subnormal results. When underflow occurs, the exponent is set
1137 to :const:`Etiny`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001138
1139
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001140 .. method:: Etop()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001141
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001142 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001143
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001144 The usual approach to working with decimals is to create :class:`Decimal`
1145 instances and then apply arithmetic operations which take place within the
1146 current context for the active thread. An alternative approach is to use
1147 context methods for calculating within a specific context. The methods are
1148 similar to those for the :class:`Decimal` class and are only briefly
1149 recounted here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001150
1151
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001152 .. method:: abs(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001153
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001154 Returns the absolute value of *x*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001155
1156
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001157 .. method:: add(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001158
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001159 Return the sum of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001160
1161
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001162 .. method:: canonical(x)
1163
1164 Returns the same Decimal object *x*.
1165
1166
1167 .. method:: compare(x, y)
1168
1169 Compares *x* and *y* numerically.
1170
1171
1172 .. method:: compare_signal(x, y)
1173
1174 Compares the values of the two operands numerically.
1175
1176
1177 .. method:: compare_total(x, y)
1178
1179 Compares two operands using their abstract representation.
1180
1181
1182 .. method:: compare_total_mag(x, y)
1183
1184 Compares two operands using their abstract representation, ignoring sign.
1185
1186
1187 .. method:: copy_abs(x)
1188
1189 Returns a copy of *x* with the sign set to 0.
1190
1191
1192 .. method:: copy_negate(x)
1193
1194 Returns a copy of *x* with the sign inverted.
1195
1196
1197 .. method:: copy_sign(x, y)
1198
1199 Copies the sign from *y* to *x*.
1200
1201
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001202 .. method:: divide(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001203
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001204 Return *x* divided by *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001205
1206
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001207 .. method:: divide_int(x, y)
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001208
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001209 Return *x* divided by *y*, truncated to an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001210
1211
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001212 .. method:: divmod(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001213
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001214 Divides two numbers and returns the integer part of the result.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001215
1216
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001217 .. method:: exp(x)
1218
1219 Returns `e ** x`.
1220
1221
1222 .. method:: fma(x, y, z)
1223
1224 Returns *x* multiplied by *y*, plus *z*.
1225
1226
1227 .. method:: is_canonical(x)
1228
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001229 Returns ``True`` if *x* is canonical; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001230
1231
1232 .. method:: is_finite(x)
1233
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001234 Returns ``True`` if *x* is finite; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001235
1236
1237 .. method:: is_infinite(x)
1238
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001239 Returns ``True`` if *x* is infinite; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001240
1241
1242 .. method:: is_nan(x)
1243
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001244 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001245
1246
1247 .. method:: is_normal(x)
1248
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001249 Returns ``True`` if *x* is a normal number; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001250
1251
1252 .. method:: is_qnan(x)
1253
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001254 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001255
1256
1257 .. method:: is_signed(x)
1258
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001259 Returns ``True`` if *x* is negative; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001260
1261
1262 .. method:: is_snan(x)
1263
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001264 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001265
1266
1267 .. method:: is_subnormal(x)
1268
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001269 Returns ``True`` if *x* is subnormal; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001270
1271
1272 .. method:: is_zero(x)
1273
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001274 Returns ``True`` if *x* is a zero; otherwise returns ``False``.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001275
1276
1277 .. method:: ln(x)
1278
1279 Returns the natural (base e) logarithm of *x*.
1280
1281
1282 .. method:: log10(x)
1283
1284 Returns the base 10 logarithm of *x*.
1285
1286
1287 .. method:: logb(x)
1288
1289 Returns the exponent of the magnitude of the operand's MSD.
1290
1291
1292 .. method:: logical_and(x, y)
1293
Georg Brandle92818f2009-01-03 20:47:01 +00001294 Applies the logical operation *and* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001295
1296
1297 .. method:: logical_invert(x)
1298
1299 Invert all the digits in *x*.
1300
1301
1302 .. method:: logical_or(x, y)
1303
Georg Brandle92818f2009-01-03 20:47:01 +00001304 Applies the logical operation *or* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001305
1306
1307 .. method:: logical_xor(x, y)
1308
Georg Brandle92818f2009-01-03 20:47:01 +00001309 Applies the logical operation *xor* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001310
1311
1312 .. method:: max(x, y)
1313
1314 Compares two values numerically and returns the maximum.
1315
1316
1317 .. method:: max_mag(x, y)
1318
1319 Compares the values numerically with their sign ignored.
1320
1321
1322 .. method:: min(x, y)
1323
1324 Compares two values numerically and returns the minimum.
1325
1326
1327 .. method:: min_mag(x, y)
1328
1329 Compares the values numerically with their sign ignored.
1330
1331
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001332 .. method:: minus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001333
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001334 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001335
1336
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001337 .. method:: multiply(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001338
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001339 Return the product of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001340
1341
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001342 .. method:: next_minus(x)
1343
1344 Returns the largest representable number smaller than *x*.
1345
1346
1347 .. method:: next_plus(x)
1348
1349 Returns the smallest representable number larger than *x*.
1350
1351
1352 .. method:: next_toward(x, y)
1353
1354 Returns the number closest to *x*, in direction towards *y*.
1355
1356
1357 .. method:: normalize(x)
1358
1359 Reduces *x* to its simplest form.
1360
1361
1362 .. method:: number_class(x)
1363
1364 Returns an indication of the class of *x*.
1365
1366
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001367 .. method:: plus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001368
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001369 Plus corresponds to the unary prefix plus operator in Python. This
1370 operation applies the context precision and rounding, so it is *not* an
1371 identity operation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001372
1373
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001374 .. method:: power(x, y[, modulo])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001375
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001376 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001377
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001378 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1379 must be integral. The result will be inexact unless ``y`` is integral and
1380 the result is finite and can be expressed exactly in 'precision' digits.
1381 The result should always be correctly rounded, using the rounding mode of
1382 the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001383
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001384 With three arguments, compute ``(x**y) % modulo``. For the three argument
1385 form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001386
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001387 - all three arguments must be integral
1388 - ``y`` must be nonnegative
1389 - at least one of ``x`` or ``y`` must be nonzero
1390 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001391
Mark Dickinsonf5be4e62010-02-22 15:40:28 +00001392 The value resulting from ``Context.power(x, y, modulo)`` is
1393 equal to the value that would be obtained by computing ``(x**y)
1394 % modulo`` with unbounded precision, but is computed more
1395 efficiently. The exponent of the result is zero, regardless of
1396 the exponents of ``x``, ``y`` and ``modulo``. The result is
1397 always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001398
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001399 .. versionchanged:: 2.6
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001400 ``y`` may now be nonintegral in ``x**y``.
1401 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001402
1403
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001404 .. method:: quantize(x, y)
1405
1406 Returns a value equal to *x* (rounded), having the exponent of *y*.
1407
1408
1409 .. method:: radix()
1410
1411 Just returns 10, as this is Decimal, :)
1412
1413
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001414 .. method:: remainder(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001415
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001416 Returns the remainder from integer division.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001417
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001418 The sign of the result, if non-zero, is the same as that of the original
1419 dividend.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001420
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001421 .. method:: remainder_near(x, y)
1422
Georg Brandle92818f2009-01-03 20:47:01 +00001423 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1424 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001425
1426
1427 .. method:: rotate(x, y)
1428
1429 Returns a rotated copy of *x*, *y* times.
1430
1431
1432 .. method:: same_quantum(x, y)
1433
Serhiy Storchaka9f91d352013-11-26 17:32:03 +02001434 Returns ``True`` if the two operands have the same exponent.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001435
1436
1437 .. method:: scaleb (x, y)
1438
1439 Returns the first operand after adding the second value its exp.
1440
1441
1442 .. method:: shift(x, y)
1443
1444 Returns a shifted copy of *x*, *y* times.
1445
1446
1447 .. method:: sqrt(x)
1448
1449 Square root of a non-negative number to context precision.
1450
1451
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001452 .. method:: subtract(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001453
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001454 Return the difference between *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001455
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001456
1457 .. method:: to_eng_string(x)
1458
1459 Converts a number to a string, using scientific notation.
1460
1461
1462 .. method:: to_integral_exact(x)
1463
1464 Rounds to an integer.
1465
1466
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001467 .. method:: to_sci_string(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001468
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001469 Converts a number to a string using scientific notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001470
Georg Brandlb19be572007-12-29 10:57:00 +00001471.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001472
1473
1474.. _decimal-signals:
1475
1476Signals
1477-------
1478
1479Signals represent conditions that arise during computation. Each corresponds to
1480one context flag and one context trap enabler.
1481
Mark Dickinson1840c1a2008-05-03 18:23:14 +00001482The context flag is set whenever the condition is encountered. After the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001483computation, flags may be checked for informational purposes (for instance, to
1484determine whether a computation was exact). After checking the flags, be sure to
1485clear all flags before starting the next computation.
1486
1487If the context's trap enabler is set for the signal, then the condition causes a
1488Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1489is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1490condition.
1491
1492
1493.. class:: Clamped
1494
1495 Altered an exponent to fit representation constraints.
1496
1497 Typically, clamping occurs when an exponent falls outside the context's
1498 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001499 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001500
1501
1502.. class:: DecimalException
1503
1504 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1505
1506
1507.. class:: DivisionByZero
1508
1509 Signals the division of a non-infinite number by zero.
1510
1511 Can occur with division, modulo division, or when raising a number to a negative
1512 power. If this signal is not trapped, returns :const:`Infinity` or
1513 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1514
1515
1516.. class:: Inexact
1517
1518 Indicates that rounding occurred and the result is not exact.
1519
1520 Signals when non-zero digits were discarded during rounding. The rounded result
1521 is returned. The signal flag or trap is used to detect when results are
1522 inexact.
1523
1524
1525.. class:: InvalidOperation
1526
1527 An invalid operation was performed.
1528
1529 Indicates that an operation was requested that does not make sense. If not
1530 trapped, returns :const:`NaN`. Possible causes include::
1531
1532 Infinity - Infinity
1533 0 * Infinity
1534 Infinity / Infinity
1535 x % 0
1536 Infinity % x
1537 x._rescale( non-integer )
1538 sqrt(-x) and x > 0
1539 0 ** 0
1540 x ** (non-integer)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001541 x ** Infinity
Georg Brandl8ec7f652007-08-15 14:28:01 +00001542
1543
1544.. class:: Overflow
1545
1546 Numerical overflow.
1547
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001548 Indicates the exponent is larger than :attr:`Emax` after rounding has
1549 occurred. If not trapped, the result depends on the rounding mode, either
1550 pulling inward to the largest representable finite number or rounding outward
1551 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1552 are also signaled.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001553
1554
1555.. class:: Rounded
1556
1557 Rounding occurred though possibly no information was lost.
1558
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001559 Signaled whenever rounding discards digits; even if those digits are zero
1560 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1561 the result unchanged. This signal is used to detect loss of significant
1562 digits.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001563
1564
1565.. class:: Subnormal
1566
1567 Exponent was lower than :attr:`Emin` prior to rounding.
1568
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001569 Occurs when an operation result is subnormal (the exponent is too small). If
1570 not trapped, returns the result unchanged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001571
1572
1573.. class:: Underflow
1574
1575 Numerical underflow with result rounded to zero.
1576
1577 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1578 and :class:`Subnormal` are also signaled.
1579
1580The following table summarizes the hierarchy of signals::
1581
1582 exceptions.ArithmeticError(exceptions.StandardError)
1583 DecimalException
1584 Clamped
1585 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1586 Inexact
1587 Overflow(Inexact, Rounded)
1588 Underflow(Inexact, Rounded, Subnormal)
1589 InvalidOperation
1590 Rounded
1591 Subnormal
1592
Georg Brandlb19be572007-12-29 10:57:00 +00001593.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001594
1595
1596.. _decimal-notes:
1597
1598Floating Point Notes
1599--------------------
1600
1601
1602Mitigating round-off error with increased precision
1603^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1604
1605The use of decimal floating point eliminates decimal representation error
1606(making it possible to represent :const:`0.1` exactly); however, some operations
1607can still incur round-off error when non-zero digits exceed the fixed precision.
1608
1609The effects of round-off error can be amplified by the addition or subtraction
1610of nearly offsetting quantities resulting in loss of significance. Knuth
1611provides two instructive examples where rounded floating point arithmetic with
1612insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001613properties of addition:
1614
1615.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001616
1617 # Examples from Seminumerical Algorithms, Section 4.2.2.
1618 >>> from decimal import Decimal, getcontext
1619 >>> getcontext().prec = 8
1620
1621 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1622 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001623 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001624 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001625 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001626
1627 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1628 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001629 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001630 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001631 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001632
1633The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001634expanding the precision sufficiently to avoid loss of significance:
1635
1636.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001637
1638 >>> getcontext().prec = 20
1639 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1640 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001641 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001642 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001643 Decimal('9.51111111')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001644 >>>
Georg Brandl8ec7f652007-08-15 14:28:01 +00001645 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1646 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001647 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001648 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001649 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001650
1651
1652Special values
1653^^^^^^^^^^^^^^
1654
1655The number system for the :mod:`decimal` module provides special values
1656including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001657and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001658
1659Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1660they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1661not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1662can result from rounding beyond the limits of the largest representable number.
1663
1664The infinities are signed (affine) and can be used in arithmetic operations
1665where they get treated as very large, indeterminate numbers. For instance,
1666adding a constant to infinity gives another infinite result.
1667
1668Some operations are indeterminate and return :const:`NaN`, or if the
1669:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1670``0/0`` returns :const:`NaN` which means "not a number". This variety of
1671:const:`NaN` is quiet and, once created, will flow through other computations
1672always resulting in another :const:`NaN`. This behavior can be useful for a
1673series of computations that occasionally have missing inputs --- it allows the
1674calculation to proceed while flagging specific results as invalid.
1675
1676A variant is :const:`sNaN` which signals rather than remaining quiet after every
1677operation. This is a useful return value when an invalid result needs to
1678interrupt a calculation for special handling.
1679
Mark Dickinson2fc92632008-02-06 22:10:50 +00001680The behavior of Python's comparison operators can be a little surprising where a
1681:const:`NaN` is involved. A test for equality where one of the operands is a
1682quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1683``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001684:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001685``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1686if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001687not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001688specify the behavior of direct comparisons; these rules for comparisons
1689involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1690section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001691and :meth:`compare-signal` methods instead.
1692
Georg Brandl8ec7f652007-08-15 14:28:01 +00001693The signed zeros can result from calculations that underflow. They keep the sign
1694that would have resulted if the calculation had been carried out to greater
1695precision. Since their magnitude is zero, both positive and negative zeros are
1696treated as equal and their sign is informational.
1697
1698In addition to the two signed zeros which are distinct yet equal, there are
1699various representations of zero with differing precisions yet equivalent in
1700value. This takes a bit of getting used to. For an eye accustomed to
1701normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001702the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001703
1704 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001705 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001706
Georg Brandlb19be572007-12-29 10:57:00 +00001707.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001708
1709
1710.. _decimal-threads:
1711
1712Working with threads
1713--------------------
1714
1715The :func:`getcontext` function accesses a different :class:`Context` object for
1716each thread. Having separate thread contexts means that threads may make
1717changes (such as ``getcontext.prec=10``) without interfering with other threads.
1718
1719Likewise, the :func:`setcontext` function automatically assigns its target to
1720the current thread.
1721
1722If :func:`setcontext` has not been called before :func:`getcontext`, then
1723:func:`getcontext` will automatically create a new context for use in the
1724current thread.
1725
1726The new context is copied from a prototype context called *DefaultContext*. To
1727control the defaults so that each thread will use the same values throughout the
1728application, directly modify the *DefaultContext* object. This should be done
1729*before* any threads are started so that there won't be a race condition between
1730threads calling :func:`getcontext`. For example::
1731
1732 # Set applicationwide defaults for all threads about to be launched
1733 DefaultContext.prec = 12
1734 DefaultContext.rounding = ROUND_DOWN
1735 DefaultContext.traps = ExtendedContext.traps.copy()
1736 DefaultContext.traps[InvalidOperation] = 1
1737 setcontext(DefaultContext)
1738
1739 # Afterwards, the threads can be started
1740 t1.start()
1741 t2.start()
1742 t3.start()
1743 . . .
1744
Georg Brandlb19be572007-12-29 10:57:00 +00001745.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001746
1747
1748.. _decimal-recipes:
1749
1750Recipes
1751-------
1752
1753Here are a few recipes that serve as utility functions and that demonstrate ways
1754to work with the :class:`Decimal` class::
1755
1756 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1757 pos='', neg='-', trailneg=''):
1758 """Convert Decimal to a money formatted string.
1759
1760 places: required number of places after the decimal point
1761 curr: optional currency symbol before the sign (may be blank)
1762 sep: optional grouping separator (comma, period, space, or blank)
1763 dp: decimal point indicator (comma or period)
1764 only specify as blank when places is zero
1765 pos: optional sign for positive numbers: '+', space or blank
1766 neg: optional sign for negative numbers: '-', '(', space or blank
1767 trailneg:optional trailing minus indicator: '-', ')', space or blank
1768
1769 >>> d = Decimal('-1234567.8901')
1770 >>> moneyfmt(d, curr='$')
1771 '-$1,234,567.89'
1772 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1773 '1.234.568-'
1774 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1775 '($1,234,567.89)'
1776 >>> moneyfmt(Decimal(123456789), sep=' ')
1777 '123 456 789.00'
1778 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001779 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001780
1781 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001782 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001783 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001784 result = []
1785 digits = map(str, digits)
1786 build, next = result.append, digits.pop
1787 if sign:
1788 build(trailneg)
1789 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001790 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001791 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001792 if not digits:
1793 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001794 i = 0
1795 while digits:
1796 build(next())
1797 i += 1
1798 if i == 3 and digits:
1799 i = 0
1800 build(sep)
1801 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001802 build(neg if sign else pos)
1803 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001804
1805 def pi():
1806 """Compute Pi to the current precision.
1807
1808 >>> print pi()
1809 3.141592653589793238462643383
1810
1811 """
1812 getcontext().prec += 2 # extra digits for intermediate steps
1813 three = Decimal(3) # substitute "three=3.0" for regular floats
1814 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1815 while s != lasts:
1816 lasts = s
1817 n, na = n+na, na+8
1818 d, da = d+da, da+32
1819 t = (t * n) / d
1820 s += t
1821 getcontext().prec -= 2
1822 return +s # unary plus applies the new precision
1823
1824 def exp(x):
1825 """Return e raised to the power of x. Result type matches input type.
1826
1827 >>> print exp(Decimal(1))
1828 2.718281828459045235360287471
1829 >>> print exp(Decimal(2))
1830 7.389056098930650227230427461
1831 >>> print exp(2.0)
1832 7.38905609893
1833 >>> print exp(2+0j)
1834 (7.38905609893+0j)
1835
1836 """
1837 getcontext().prec += 2
1838 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1839 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001840 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001841 i += 1
1842 fact *= i
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001843 num *= x
1844 s += num / fact
1845 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001846 return +s
1847
1848 def cos(x):
1849 """Return the cosine of x as measured in radians.
1850
1851 >>> print cos(Decimal('0.5'))
1852 0.8775825618903727161162815826
1853 >>> print cos(0.5)
1854 0.87758256189
1855 >>> print cos(0.5+0j)
1856 (0.87758256189+0j)
1857
1858 """
1859 getcontext().prec += 2
1860 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1861 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001862 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001863 i += 2
1864 fact *= i * (i-1)
1865 num *= x * x
1866 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001867 s += num / fact * sign
1868 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001869 return +s
1870
1871 def sin(x):
1872 """Return the sine of x as measured in radians.
1873
1874 >>> print sin(Decimal('0.5'))
1875 0.4794255386042030002732879352
1876 >>> print sin(0.5)
1877 0.479425538604
1878 >>> print sin(0.5+0j)
1879 (0.479425538604+0j)
1880
1881 """
1882 getcontext().prec += 2
1883 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1884 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001885 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001886 i += 2
1887 fact *= i * (i-1)
1888 num *= x * x
1889 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001890 s += num / fact * sign
1891 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001892 return +s
1893
1894
Georg Brandlb19be572007-12-29 10:57:00 +00001895.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001896
1897
1898.. _decimal-faq:
1899
1900Decimal FAQ
1901-----------
1902
1903Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1904minimize typing when using the interactive interpreter?
1905
Georg Brandl9f662322008-03-22 11:47:10 +00001906A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001907
1908 >>> D = decimal.Decimal
1909 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001910 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001911
1912Q. In a fixed-point application with two decimal places, some inputs have many
1913places and need to be rounded. Others are not supposed to have excess digits
1914and need to be validated. What methods should be used?
1915
1916A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001917the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001918
1919 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1920
1921 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001922 >>> Decimal('3.214').quantize(TWOPLACES)
1923 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001924
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001925 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001926 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1927 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001928
Raymond Hettingerabe32372008-02-14 02:41:22 +00001929 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001930 Traceback (most recent call last):
1931 ...
Georg Brandlf6dab952009-04-28 21:48:35 +00001932 Inexact: None
Georg Brandl8ec7f652007-08-15 14:28:01 +00001933
1934Q. Once I have valid two place inputs, how do I maintain that invariant
1935throughout an application?
1936
Raymond Hettinger46314812008-02-14 10:46:57 +00001937A. Some operations like addition, subtraction, and multiplication by an integer
1938will automatically preserve fixed point. Others operations, like division and
1939non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001940be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001941
1942 >>> a = Decimal('102.72') # Initial fixed-point values
1943 >>> b = Decimal('3.17')
1944 >>> a + b # Addition preserves fixed-point
1945 Decimal('105.89')
1946 >>> a - b
1947 Decimal('99.55')
1948 >>> a * 42 # So does integer multiplication
1949 Decimal('4314.24')
1950 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1951 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001952 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001953 Decimal('0.03')
1954
1955In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001956to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001957
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001958 >>> def mul(x, y, fp=TWOPLACES):
1959 ... return (x * y).quantize(fp)
1960 >>> def div(x, y, fp=TWOPLACES):
1961 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001962
Raymond Hettinger46314812008-02-14 10:46:57 +00001963 >>> mul(a, b) # Automatically preserve fixed-point
1964 Decimal('325.62')
1965 >>> div(b, a)
1966 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001967
1968Q. There are many ways to express the same value. The numbers :const:`200`,
1969:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1970various precisions. Is there a way to transform them to a single recognizable
1971canonical value?
1972
1973A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001974representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001975
1976 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1977 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001978 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001979
1980Q. Some decimal values always print with exponential notation. Is there a way
1981to get a non-exponential representation?
1982
1983A. For some values, exponential notation is the only way to express the number
1984of significant places in the coefficient. For example, expressing
1985:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1986original's two-place significance.
1987
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001988If an application does not care about tracking significance, it is easy to
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001989remove the exponent and trailing zeros, losing significance, but keeping the
1990value unchanged::
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001991
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001992 def remove_exponent(d):
1993 '''Remove exponent and trailing zeros.
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001994
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001995 >>> remove_exponent(Decimal('5E+3'))
1996 Decimal('5000')
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001997
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001998 '''
1999 return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Georg Brandl8ec7f652007-08-15 14:28:01 +00002000
Raymond Hettingered171ab2010-04-02 18:39:24 +00002001Q. Is there a way to convert a regular float to a :class:`Decimal`?
Georg Brandl9f662322008-03-22 11:47:10 +00002002
Mark Dickinsonb1affc52010-04-04 22:09:21 +00002003A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettingered171ab2010-04-02 18:39:24 +00002004Decimal though an exact conversion may take more precision than intuition would
2005suggest:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002006
Raymond Hettingered171ab2010-04-02 18:39:24 +00002007.. doctest::
Georg Brandl8ec7f652007-08-15 14:28:01 +00002008
Raymond Hettingered171ab2010-04-02 18:39:24 +00002009 >>> Decimal(math.pi)
2010 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002011
2012Q. Within a complex calculation, how can I make sure that I haven't gotten a
2013spurious result because of insufficient precision or rounding anomalies.
2014
2015A. The decimal module makes it easy to test results. A best practice is to
2016re-run calculations using greater precision and with various rounding modes.
2017Widely differing results indicate insufficient precision, rounding mode issues,
2018ill-conditioned inputs, or a numerically unstable algorithm.
2019
2020Q. I noticed that context precision is applied to the results of operations but
2021not to the inputs. Is there anything to watch out for when mixing values of
2022different precisions?
2023
2024A. Yes. The principle is that all values are considered to be exact and so is
2025the arithmetic on those values. Only the results are rounded. The advantage
2026for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00002027results can look odd if you forget that the inputs haven't been rounded:
2028
2029.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00002030
2031 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00002032 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002033 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00002034 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002035 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002036
2037The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00002038using the unary plus operation:
2039
2040.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00002041
2042 >>> getcontext().prec = 3
2043 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00002044 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002045
2046Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00002047:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002048
2049 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002050 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002051