blob: 758dcce9e3b231fe89e2fd0b33b456f56e47f2a5 [file] [log] [blame]
Christian Heimes3feef612008-02-11 06:19:17 +00001:mod:`decimal` --- Decimal fixed point and floating point arithmetic
2====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: decimal
5 :synopsis: Implementation of the General Decimal Arithmetic Specification.
6
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
8.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
9.. moduleauthor:: Raymond Hettinger <python at rcn.com>
10.. moduleauthor:: Aahz <aahz at pobox.com>
11.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000012.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
13
Christian Heimesfe337bf2008-03-23 21:54:12 +000014.. import modules for testing inline doctests with the Sphinx doctest builder
15.. testsetup:: *
16
17 import decimal
18 import math
19 from decimal import *
20 # make sure each group gets a fresh context
21 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl116aa622007-08-15 14:28:22 +000023The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000024arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000025
Christian Heimes3feef612008-02-11 06:19:17 +000026* Decimal "is based on a floating-point model which was designed with people
27 in mind, and necessarily has a paramount guiding principle -- computers must
28 provide an arithmetic that works in the same way as the arithmetic that
29 people learn at school." -- excerpt from the decimal arithmetic specification.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031* Decimal numbers can be represented exactly. In contrast, numbers like
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000032 :const:`1.1` and :const:`2.2` do not have an exact representations in binary
33 floating point. End users typically would not expect ``1.1 + 2.2`` to display
34 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000035
36* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000038 is :const:`5.5511151231257827e-017`. While near to zero, the differences
39 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000040 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000041 equality invariants.
42
43* The decimal module incorporates a notion of significant places so that ``1.30
44 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
45 This is the customary presentation for monetary applications. For
46 multiplication, the "schoolbook" approach uses all the figures in the
47 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
48 1.20`` gives :const:`1.5600`.
49
50* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000051 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000052 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000053
Mark Dickinsond6b83d32010-11-07 11:26:24 +000054 >>> from decimal import *
Georg Brandl116aa622007-08-15 14:28:22 +000055 >>> getcontext().prec = 6
56 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000057 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000058 >>> getcontext().prec = 28
59 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000060 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000061
62* Both binary and decimal floating point are implemented in terms of published
63 standards. While the built-in float type exposes only a modest portion of its
64 capabilities, the decimal module exposes all required parts of the standard.
65 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000066 This includes an option to enforce exact arithmetic by using exceptions
67 to block any inexact operations.
68
69* The decimal module was designed to support "without prejudice, both exact
70 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
71 and rounded floating-point arithmetic." -- excerpt from the decimal
72 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74The module design is centered around three concepts: the decimal number, the
75context for arithmetic, and signals.
76
77A decimal number is immutable. It has a sign, coefficient digits, and an
78exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000079trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000080:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
81differentiates :const:`-0` from :const:`+0`.
82
83The context for arithmetic is an environment specifying precision, rounding
84rules, limits on exponents, flags indicating the results of operations, and trap
85enablers which determine whether signals are treated as exceptions. Rounding
86options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
87:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000088:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90Signals are groups of exceptional conditions arising during the course of
91computation. Depending on the needs of the application, signals may be ignored,
92considered as informational, or treated as exceptions. The signals in the
93decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
94:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
95:const:`Overflow`, and :const:`Underflow`.
96
97For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000098encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000099set to one, an exception is raised. Flags are sticky, so the user needs to
100reset them before monitoring a calculation.
101
102
103.. seealso::
104
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000105 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000106 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000109 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000111.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. _decimal-tutorial:
115
116Quick-start Tutorial
117--------------------
118
119The usual start to using decimals is importing the module, viewing the current
120context with :func:`getcontext` and, if necessary, setting new values for
121precision, rounding, or enabled traps::
122
123 >>> from decimal import *
124 >>> getcontext()
125 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000126 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
127 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 >>> getcontext().prec = 7 # Set a new precision
130
131Decimal instances can be constructed from integers, strings, or tuples. To
132create a Decimal from a :class:`float`, first convert it to a string. This
133serves as an explicit reminder of the details of the conversion (including
134representation error). Decimal numbers include special values such as
135:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000136:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Facundo Batista789bdf02008-06-21 17:29:41 +0000138 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000139 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000140 Decimal('10')
141 >>> Decimal('3.14')
142 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000143 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000144 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000145 >>> Decimal(str(2.0 ** 0.5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000146 Decimal('1.41421356237')
147 >>> Decimal(2) ** Decimal('0.5')
148 Decimal('1.414213562373095048801688724')
149 >>> Decimal('NaN')
150 Decimal('NaN')
151 >>> Decimal('-Infinity')
152 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154The significance of a new Decimal is determined solely by the number of digits
155input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000156operations.
157
158.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160 >>> getcontext().prec = 6
161 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000162 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000163 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000164 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000165 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000166 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000167 >>> getcontext().rounding = ROUND_UP
168 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000169 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000172floating point flying circus:
173
174.. doctest::
175 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Facundo Batista789bdf02008-06-21 17:29:41 +0000177 >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
Georg Brandl116aa622007-08-15 14:28:22 +0000178 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000179 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000180 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000181 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000182 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000183 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
184 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000185 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000186 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000187 >>> a,b,c = data[:3]
188 >>> str(a)
189 '1.34'
190 >>> float(a)
Mark Dickinsoncf2d9ff2009-06-28 20:38:24 +0000191 1.34
192 >>> round(a, 1)
193 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000194 >>> int(a)
195 1
196 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000197 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000198 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000199 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000200 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000201 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Christian Heimesfe337bf2008-03-23 21:54:12 +0000203And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000204
Facundo Batista789bdf02008-06-21 17:29:41 +0000205 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000206 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000207 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000209 Decimal('2.718281828459045235360287471')
210 >>> Decimal('10').ln()
211 Decimal('2.302585092994045684017991455')
212 >>> Decimal('10').log10()
213 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000214
Georg Brandl116aa622007-08-15 14:28:22 +0000215The :meth:`quantize` method rounds a number to a fixed exponent. This method is
216useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000217places:
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000220 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000221 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000222 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224As shown above, the :func:`getcontext` function accesses the current context and
225allows the settings to be changed. This approach meets the needs of most
226applications.
227
228For more advanced work, it may be useful to create alternate contexts using the
229Context() constructor. To make an alternate active, use the :func:`setcontext`
230function.
231
232In accordance with the standard, the :mod:`Decimal` module provides two ready to
233use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
234former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000235enabled:
236
237.. doctest:: newcontext
238 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
241 >>> setcontext(myothercontext)
242 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000243 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245 >>> ExtendedContext
246 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
247 capitals=1, flags=[], traps=[])
248 >>> setcontext(ExtendedContext)
249 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000250 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000251 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000252 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254 >>> setcontext(BasicContext)
255 >>> Decimal(42) / Decimal(0)
256 Traceback (most recent call last):
257 File "<pyshell#143>", line 1, in -toplevel-
258 Decimal(42) / Decimal(0)
259 DivisionByZero: x / 0
260
261Contexts also have signal flags for monitoring exceptional conditions
262encountered during computations. The flags remain set until explicitly cleared,
263so it is best to clear the flags before each set of monitored computations by
264using the :meth:`clear_flags` method. ::
265
266 >>> setcontext(ExtendedContext)
267 >>> getcontext().clear_flags()
268 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000269 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000270 >>> getcontext()
271 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Facundo Batista789bdf02008-06-21 17:29:41 +0000272 capitals=1, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274The *flags* entry shows that the rational approximation to :const:`Pi` was
275rounded (digits beyond the context precision were thrown away) and that the
276result is inexact (some of the discarded digits were non-zero).
277
278Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000279context:
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Christian Heimesfe337bf2008-03-23 21:54:12 +0000281.. doctest:: newcontext
282
283 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000284 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000285 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000286 >>> getcontext().traps[DivisionByZero] = 1
287 >>> Decimal(1) / Decimal(0)
288 Traceback (most recent call last):
289 File "<pyshell#112>", line 1, in -toplevel-
290 Decimal(1) / Decimal(0)
291 DivisionByZero: x / 0
292
293Most programs adjust the current context only once, at the beginning of the
294program. And, in many applications, data is converted to :class:`Decimal` with
295a single cast inside a loop. With context set and decimals created, the bulk of
296the program manipulates the data no differently than with other Python numeric
297types.
298
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000299.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301
302.. _decimal-decimal:
303
304Decimal objects
305---------------
306
307
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000308.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000310 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Christian Heimesa62da1d2008-01-12 19:39:10 +0000312 *value* can be an integer, string, tuple, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000313 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000314 string, it should conform to the decimal numeric string syntax after leading
315 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317 sign ::= '+' | '-'
318 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
319 indicator ::= 'e' | 'E'
320 digits ::= digit [digit]...
321 decimal-part ::= digits '.' [digits] | ['.'] digits
322 exponent-part ::= indicator [sign] digits
323 infinity ::= 'Infinity' | 'Inf'
324 nan ::= 'NaN' [digits] | 'sNaN' [digits]
325 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000326 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Mark Dickinson8d238292009-08-02 10:16:33 +0000328 Other Unicode decimal digits are also permitted where ``digit``
329 appears above. These include decimal digits from various other
330 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
331 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333 If *value* is a :class:`tuple`, it should have three components, a sign
334 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
335 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000336 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338 The *context* precision does not affect how many digits are stored. That is
339 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000340 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000341 only three.
342
343 The purpose of the *context* argument is determining what to do if *value* is a
344 malformed string. If the context traps :const:`InvalidOperation`, an exception
345 is raised; otherwise, the constructor returns a new Decimal with the value of
346 :const:`NaN`.
347
348 Once constructed, :class:`Decimal` objects are immutable.
349
Benjamin Petersone41251e2008-04-25 01:59:09 +0000350 Decimal floating point objects share many properties with the other built-in
351 numeric types such as :class:`float` and :class:`int`. All of the usual math
352 operations and special methods apply. Likewise, decimal objects can be
353 copied, pickled, printed, used as dictionary keys, used as set elements,
354 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson9b3bada2010-02-18 14:59:50 +0000355 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000356
Benjamin Petersone41251e2008-04-25 01:59:09 +0000357 In addition to the standard numeric properties, decimal floating point
358 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Benjamin Petersone41251e2008-04-25 01:59:09 +0000361 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Benjamin Petersone41251e2008-04-25 01:59:09 +0000363 Return the adjusted exponent after shifting out the coefficient's
364 rightmost digits until only the lead digit remains:
365 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
366 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Benjamin Petersone41251e2008-04-25 01:59:09 +0000369 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Benjamin Petersone41251e2008-04-25 01:59:09 +0000371 Return a :term:`named tuple` representation of the number:
372 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Christian Heimes25bb7832008-01-11 16:17:00 +0000374
Benjamin Petersone41251e2008-04-25 01:59:09 +0000375 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Benjamin Petersone41251e2008-04-25 01:59:09 +0000377 Return the canonical encoding of the argument. Currently, the encoding of
378 a :class:`Decimal` instance is always canonical, so this operation returns
379 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380
Benjamin Petersone41251e2008-04-25 01:59:09 +0000381 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382
Georg Brandl05f5ab72008-09-24 09:11:47 +0000383 Compare the values of two Decimal instances. :meth:`compare` returns a
384 Decimal instance, and if either operand is a NaN then the result is a
385 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000386
Georg Brandl05f5ab72008-09-24 09:11:47 +0000387 a or b is a NaN ==> Decimal('NaN')
388 a < b ==> Decimal('-1')
389 a == b ==> Decimal('0')
390 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Benjamin Petersone41251e2008-04-25 01:59:09 +0000392 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Benjamin Petersone41251e2008-04-25 01:59:09 +0000394 This operation is identical to the :meth:`compare` method, except that all
395 NaNs signal. That is, if neither operand is a signaling NaN then any
396 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Benjamin Petersone41251e2008-04-25 01:59:09 +0000398 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399
Benjamin Petersone41251e2008-04-25 01:59:09 +0000400 Compare two operands using their abstract representation rather than their
401 numerical value. Similar to the :meth:`compare` method, but the result
402 gives a total ordering on :class:`Decimal` instances. Two
403 :class:`Decimal` instances with the same numeric value but different
404 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000405
Benjamin Petersone41251e2008-04-25 01:59:09 +0000406 >>> Decimal('12.0').compare_total(Decimal('12'))
407 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000408
Benjamin Petersone41251e2008-04-25 01:59:09 +0000409 Quiet and signaling NaNs are also included in the total ordering. The
410 result of this function is ``Decimal('0')`` if both operands have the same
411 representation, ``Decimal('-1')`` if the first operand is lower in the
412 total order than the second, and ``Decimal('1')`` if the first operand is
413 higher in the total order than the second operand. See the specification
414 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000415
Benjamin Petersone41251e2008-04-25 01:59:09 +0000416 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000417
Benjamin Petersone41251e2008-04-25 01:59:09 +0000418 Compare two operands using their abstract representation rather than their
419 value as in :meth:`compare_total`, but ignoring the sign of each operand.
420 ``x.compare_total_mag(y)`` is equivalent to
421 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000422
Facundo Batista789bdf02008-06-21 17:29:41 +0000423 .. method:: conjugate()
424
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000425 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000426 Specification.
427
Benjamin Petersone41251e2008-04-25 01:59:09 +0000428 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000429
Benjamin Petersone41251e2008-04-25 01:59:09 +0000430 Return the absolute value of the argument. This operation is unaffected
431 by the context and is quiet: no flags are changed and no rounding is
432 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000433
Benjamin Petersone41251e2008-04-25 01:59:09 +0000434 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000435
Benjamin Petersone41251e2008-04-25 01:59:09 +0000436 Return the negation of the argument. This operation is unaffected by the
437 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440
Benjamin Petersone41251e2008-04-25 01:59:09 +0000441 Return a copy of the first operand with the sign set to be the same as the
442 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000443
Benjamin Petersone41251e2008-04-25 01:59:09 +0000444 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
445 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000446
Benjamin Petersone41251e2008-04-25 01:59:09 +0000447 This operation is unaffected by the context and is quiet: no flags are
448 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
Benjamin Petersone41251e2008-04-25 01:59:09 +0000450 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 Return the value of the (natural) exponential function ``e**x`` at the
453 given number. The result is correctly rounded using the
454 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000455
Benjamin Petersone41251e2008-04-25 01:59:09 +0000456 >>> Decimal(1).exp()
457 Decimal('2.718281828459045235360287471')
458 >>> Decimal(321).exp()
459 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460
Raymond Hettinger771ed762009-01-03 19:20:32 +0000461 .. method:: from_float(f)
462
463 Classmethod that converts a float to a decimal number, exactly.
464
465 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
466 Since 0.1 is not exactly representable in binary floating point, the
467 value is stored as the nearest representable value which is
468 `0x1.999999999999ap-4`. That equivalent value in decimal is
469 `0.1000000000000000055511151231257827021181583404541015625`.
470
471 .. doctest::
472
473 >>> Decimal.from_float(0.1)
474 Decimal('0.1000000000000000055511151231257827021181583404541015625')
475 >>> Decimal.from_float(float('nan'))
476 Decimal('NaN')
477 >>> Decimal.from_float(float('inf'))
478 Decimal('Infinity')
479 >>> Decimal.from_float(float('-inf'))
480 Decimal('-Infinity')
481
Georg Brandl45f53372009-01-03 21:15:20 +0000482 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000483
Benjamin Petersone41251e2008-04-25 01:59:09 +0000484 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Benjamin Petersone41251e2008-04-25 01:59:09 +0000486 Fused multiply-add. Return self*other+third with no rounding of the
487 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 >>> Decimal(2).fma(3, 5)
490 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491
Benjamin Petersone41251e2008-04-25 01:59:09 +0000492 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Benjamin Petersone41251e2008-04-25 01:59:09 +0000494 Return :const:`True` if the argument is canonical and :const:`False`
495 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
496 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
Benjamin Petersone41251e2008-04-25 01:59:09 +0000498 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499
Benjamin Petersone41251e2008-04-25 01:59:09 +0000500 Return :const:`True` if the argument is a finite number, and
501 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502
Benjamin Petersone41251e2008-04-25 01:59:09 +0000503 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
Benjamin Petersone41251e2008-04-25 01:59:09 +0000505 Return :const:`True` if the argument is either positive or negative
506 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507
Benjamin Petersone41251e2008-04-25 01:59:09 +0000508 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509
Benjamin Petersone41251e2008-04-25 01:59:09 +0000510 Return :const:`True` if the argument is a (quiet or signaling) NaN and
511 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512
Benjamin Petersone41251e2008-04-25 01:59:09 +0000513 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000514
Benjamin Petersone41251e2008-04-25 01:59:09 +0000515 Return :const:`True` if the argument is a *normal* finite number. Return
516 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517
Benjamin Petersone41251e2008-04-25 01:59:09 +0000518 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519
Benjamin Petersone41251e2008-04-25 01:59:09 +0000520 Return :const:`True` if the argument is a quiet NaN, and
521 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
Benjamin Petersone41251e2008-04-25 01:59:09 +0000523 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524
Benjamin Petersone41251e2008-04-25 01:59:09 +0000525 Return :const:`True` if the argument has a negative sign and
526 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000527
Benjamin Petersone41251e2008-04-25 01:59:09 +0000528 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
Benjamin Petersone41251e2008-04-25 01:59:09 +0000530 Return :const:`True` if the argument is a signaling NaN and :const:`False`
531 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
Benjamin Petersone41251e2008-04-25 01:59:09 +0000533 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534
Benjamin Petersone41251e2008-04-25 01:59:09 +0000535 Return :const:`True` if the argument is subnormal, and :const:`False`
536 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
Benjamin Petersone41251e2008-04-25 01:59:09 +0000538 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539
Benjamin Petersone41251e2008-04-25 01:59:09 +0000540 Return :const:`True` if the argument is a (positive or negative) zero and
541 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
Benjamin Petersone41251e2008-04-25 01:59:09 +0000543 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
Benjamin Petersone41251e2008-04-25 01:59:09 +0000545 Return the natural (base e) logarithm of the operand. The result is
546 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547
Benjamin Petersone41251e2008-04-25 01:59:09 +0000548 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Benjamin Petersone41251e2008-04-25 01:59:09 +0000550 Return the base ten logarithm of the operand. The result is correctly
551 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552
Benjamin Petersone41251e2008-04-25 01:59:09 +0000553 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554
Benjamin Petersone41251e2008-04-25 01:59:09 +0000555 For a nonzero number, return the adjusted exponent of its operand as a
556 :class:`Decimal` instance. If the operand is a zero then
557 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
558 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
559 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
Benjamin Petersone41251e2008-04-25 01:59:09 +0000561 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562
Benjamin Petersone41251e2008-04-25 01:59:09 +0000563 :meth:`logical_and` is a logical operation which takes two *logical
564 operands* (see :ref:`logical_operands_label`). The result is the
565 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566
Georg Brandlbcc484e2009-08-13 11:51:54 +0000567 .. method:: logical_invert([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Georg Brandlbcc484e2009-08-13 11:51:54 +0000569 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000570 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
Benjamin Petersone41251e2008-04-25 01:59:09 +0000572 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000573
Benjamin Petersone41251e2008-04-25 01:59:09 +0000574 :meth:`logical_or` is a logical operation which takes two *logical
575 operands* (see :ref:`logical_operands_label`). The result is the
576 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
Benjamin Petersone41251e2008-04-25 01:59:09 +0000578 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579
Benjamin Petersone41251e2008-04-25 01:59:09 +0000580 :meth:`logical_xor` is a logical operation which takes two *logical
581 operands* (see :ref:`logical_operands_label`). The result is the
582 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585
Benjamin Petersone41251e2008-04-25 01:59:09 +0000586 Like ``max(self, other)`` except that the context rounding rule is applied
587 before returning and that :const:`NaN` values are either signaled or
588 ignored (depending on the context and whether they are signaling or
589 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
Benjamin Petersone41251e2008-04-25 01:59:09 +0000591 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Georg Brandlc5605df2009-08-13 08:26:44 +0000593 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000594 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Benjamin Petersone41251e2008-04-25 01:59:09 +0000596 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Benjamin Petersone41251e2008-04-25 01:59:09 +0000598 Like ``min(self, other)`` except that the context rounding rule is applied
599 before returning and that :const:`NaN` values are either signaled or
600 ignored (depending on the context and whether they are signaling or
601 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Benjamin Petersone41251e2008-04-25 01:59:09 +0000603 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Georg Brandlc5605df2009-08-13 08:26:44 +0000605 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000606 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607
Benjamin Petersone41251e2008-04-25 01:59:09 +0000608 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 Return the largest number representable in the given context (or in the
611 current thread's context if no context is given) that is smaller than the
612 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Benjamin Petersone41251e2008-04-25 01:59:09 +0000614 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Benjamin Petersone41251e2008-04-25 01:59:09 +0000616 Return the smallest number representable in the given context (or in the
617 current thread's context if no context is given) that is larger than the
618 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000619
Benjamin Petersone41251e2008-04-25 01:59:09 +0000620 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Benjamin Petersone41251e2008-04-25 01:59:09 +0000622 If the two operands are unequal, return the number closest to the first
623 operand in the direction of the second operand. If both operands are
624 numerically equal, return a copy of the first operand with the sign set to
625 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Benjamin Petersone41251e2008-04-25 01:59:09 +0000627 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Benjamin Petersone41251e2008-04-25 01:59:09 +0000629 Normalize the number by stripping the rightmost trailing zeros and
630 converting any result equal to :const:`Decimal('0')` to
631 :const:`Decimal('0e0')`. Used for producing canonical values for members
632 of an equivalence class. For example, ``Decimal('32.100')`` and
633 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
634 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635
Benjamin Petersone41251e2008-04-25 01:59:09 +0000636 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637
Benjamin Petersone41251e2008-04-25 01:59:09 +0000638 Return a string describing the *class* of the operand. The returned value
639 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Benjamin Petersone41251e2008-04-25 01:59:09 +0000641 * ``"-Infinity"``, indicating that the operand is negative infinity.
642 * ``"-Normal"``, indicating that the operand is a negative normal number.
643 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
644 * ``"-Zero"``, indicating that the operand is a negative zero.
645 * ``"+Zero"``, indicating that the operand is a positive zero.
646 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
647 * ``"+Normal"``, indicating that the operand is a positive normal number.
648 * ``"+Infinity"``, indicating that the operand is positive infinity.
649 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
650 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Benjamin Petersone41251e2008-04-25 01:59:09 +0000654 Return a value equal to the first operand after rounding and having the
655 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
Benjamin Petersone41251e2008-04-25 01:59:09 +0000657 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
658 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659
Benjamin Petersone41251e2008-04-25 01:59:09 +0000660 Unlike other operations, if the length of the coefficient after the
661 quantize operation would be greater than precision, then an
662 :const:`InvalidOperation` is signaled. This guarantees that, unless there
663 is an error condition, the quantized exponent is always equal to that of
664 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Benjamin Petersone41251e2008-04-25 01:59:09 +0000666 Also unlike other operations, quantize never signals Underflow, even if
667 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
Benjamin Petersone41251e2008-04-25 01:59:09 +0000669 If the exponent of the second operand is larger than that of the first
670 then rounding may be necessary. In this case, the rounding mode is
671 determined by the ``rounding`` argument if given, else by the given
672 ``context`` argument; if neither argument is given the rounding mode of
673 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000674
Benjamin Petersone41251e2008-04-25 01:59:09 +0000675 If *watchexp* is set (default), then an error is returned whenever the
676 resulting exponent is greater than :attr:`Emax` or less than
677 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Benjamin Petersone41251e2008-04-25 01:59:09 +0000679 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680
Benjamin Petersone41251e2008-04-25 01:59:09 +0000681 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
682 class does all its arithmetic. Included for compatibility with the
683 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Benjamin Petersone41251e2008-04-25 01:59:09 +0000685 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Benjamin Petersone41251e2008-04-25 01:59:09 +0000687 Compute the modulo as either a positive or negative value depending on
688 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
689 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000690
Benjamin Petersone41251e2008-04-25 01:59:09 +0000691 If both are equally close, the one chosen will have the same sign as
692 *self*.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Benjamin Petersone41251e2008-04-25 01:59:09 +0000694 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Benjamin Petersone41251e2008-04-25 01:59:09 +0000696 Return the result of rotating the digits of the first operand by an amount
697 specified by the second operand. The second operand must be an integer in
698 the range -precision through precision. The absolute value of the second
699 operand gives the number of places to rotate. If the second operand is
700 positive then rotation is to the left; otherwise rotation is to the right.
701 The coefficient of the first operand is padded on the left with zeros to
702 length precision if necessary. The sign and exponent of the first operand
703 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704
Benjamin Petersone41251e2008-04-25 01:59:09 +0000705 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Benjamin Petersone41251e2008-04-25 01:59:09 +0000707 Test whether self and other have the same exponent or whether both are
708 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709
Benjamin Petersone41251e2008-04-25 01:59:09 +0000710 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
Benjamin Petersone41251e2008-04-25 01:59:09 +0000712 Return the first operand with exponent adjusted by the second.
713 Equivalently, return the first operand multiplied by ``10**other``. The
714 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Benjamin Petersone41251e2008-04-25 01:59:09 +0000716 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Benjamin Petersone41251e2008-04-25 01:59:09 +0000718 Return the result of shifting the digits of the first operand by an amount
719 specified by the second operand. The second operand must be an integer in
720 the range -precision through precision. The absolute value of the second
721 operand gives the number of places to shift. If the second operand is
722 positive then the shift is to the left; otherwise the shift is to the
723 right. Digits shifted into the coefficient are zeros. The sign and
724 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Petersone41251e2008-04-25 01:59:09 +0000726 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Benjamin Petersone41251e2008-04-25 01:59:09 +0000728 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Benjamin Petersone41251e2008-04-25 01:59:09 +0000731 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Benjamin Petersone41251e2008-04-25 01:59:09 +0000733 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000734
Benjamin Petersone41251e2008-04-25 01:59:09 +0000735 Engineering notation has an exponent which is a multiple of 3, so there
736 are up to 3 digits left of the decimal place. For example, converts
737 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738
Benjamin Petersone41251e2008-04-25 01:59:09 +0000739 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Benjamin Petersone41251e2008-04-25 01:59:09 +0000741 Identical to the :meth:`to_integral_value` method. The ``to_integral``
742 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743
Benjamin Petersone41251e2008-04-25 01:59:09 +0000744 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Benjamin Petersone41251e2008-04-25 01:59:09 +0000746 Round to the nearest integer, signaling :const:`Inexact` or
747 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
748 determined by the ``rounding`` parameter if given, else by the given
749 ``context``. If neither parameter is given then the rounding mode of the
750 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
Benjamin Petersone41251e2008-04-25 01:59:09 +0000752 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Benjamin Petersone41251e2008-04-25 01:59:09 +0000754 Round to the nearest integer without signaling :const:`Inexact` or
755 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
756 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
759.. _logical_operands_label:
760
761Logical operands
762^^^^^^^^^^^^^^^^
763
764The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
765and :meth:`logical_xor` methods expect their arguments to be *logical
766operands*. A *logical operand* is a :class:`Decimal` instance whose
767exponent and sign are both zero, and whose digits are all either
768:const:`0` or :const:`1`.
769
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000770.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772
773.. _decimal-context:
774
775Context objects
776---------------
777
778Contexts are environments for arithmetic operations. They govern precision, set
779rules for rounding, determine which signals are treated as exceptions, and limit
780the range for exponents.
781
782Each thread has its own current context which is accessed or changed using the
783:func:`getcontext` and :func:`setcontext` functions:
784
785
786.. function:: getcontext()
787
788 Return the current context for the active thread.
789
790
791.. function:: setcontext(c)
792
793 Set the current context for the active thread to *c*.
794
Georg Brandle6bcc912008-05-12 18:05:20 +0000795You can also use the :keyword:`with` statement and the :func:`localcontext`
796function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000797
798.. function:: localcontext([c])
799
800 Return a context manager that will set the current context for the active thread
801 to a copy of *c* on entry to the with-statement and restore the previous context
802 when exiting the with-statement. If no context is specified, a copy of the
803 current context is used.
804
Georg Brandl116aa622007-08-15 14:28:22 +0000805 For example, the following code sets the current decimal precision to 42 places,
806 performs a calculation, and then automatically restores the previous context::
807
Georg Brandl116aa622007-08-15 14:28:22 +0000808 from decimal import localcontext
809
810 with localcontext() as ctx:
811 ctx.prec = 42 # Perform a high precision calculation
812 s = calculate_something()
813 s = +s # Round the final result back to the default precision
814
815New contexts can also be created using the :class:`Context` constructor
816described below. In addition, the module provides three pre-made contexts:
817
818
819.. class:: BasicContext
820
821 This is a standard context defined by the General Decimal Arithmetic
822 Specification. Precision is set to nine. Rounding is set to
823 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
824 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
825 :const:`Subnormal`.
826
827 Because many of the traps are enabled, this context is useful for debugging.
828
829
830.. class:: ExtendedContext
831
832 This is a standard context defined by the General Decimal Arithmetic
833 Specification. Precision is set to nine. Rounding is set to
834 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
835 exceptions are not raised during computations).
836
Christian Heimes3feef612008-02-11 06:19:17 +0000837 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000838 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
839 raising exceptions. This allows an application to complete a run in the
840 presence of conditions that would otherwise halt the program.
841
842
843.. class:: DefaultContext
844
845 This context is used by the :class:`Context` constructor as a prototype for new
846 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Krah3e2d67e2010-05-29 13:01:02 +0000847 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000848
849 This context is most useful in multi-threaded environments. Changing one of the
850 fields before threads are started has the effect of setting system-wide
851 defaults. Changing the fields after threads have started is not recommended as
852 it would require thread synchronization to prevent race conditions.
853
854 In single threaded environments, it is preferable to not use this context at
855 all. Instead, simply create contexts explicitly as described below.
856
857 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
858 for Overflow, InvalidOperation, and DivisionByZero.
859
860In addition to the three supplied contexts, new contexts can be created with the
861:class:`Context` constructor.
862
863
864.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
865
866 Creates a new context. If a field is not specified or is :const:`None`, the
867 default values are copied from the :const:`DefaultContext`. If the *flags*
868 field is not specified or is :const:`None`, all flags are cleared.
869
870 The *prec* field is a positive integer that sets the precision for arithmetic
871 operations in the context.
872
873 The *rounding* option is one of:
874
875 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
876 * :const:`ROUND_DOWN` (towards zero),
877 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
878 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
879 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
880 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
881 * :const:`ROUND_UP` (away from zero).
Georg Brandl48310cd2009-01-03 21:18:54 +0000882 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885 The *traps* and *flags* fields list any signals to be set. Generally, new
886 contexts should only set traps and leave the flags clear.
887
888 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
889 for exponents.
890
891 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
892 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
893 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
894
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Benjamin Petersone41251e2008-04-25 01:59:09 +0000896 The :class:`Context` class defines several general purpose methods as well as
897 a large number of methods for doing arithmetic directly in a given context.
898 In addition, for each of the :class:`Decimal` methods described above (with
899 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
900 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
901 equivalent to ``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000902
903
Benjamin Petersone41251e2008-04-25 01:59:09 +0000904 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Benjamin Petersone41251e2008-04-25 01:59:09 +0000906 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000907
Benjamin Petersone41251e2008-04-25 01:59:09 +0000908 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Benjamin Petersone41251e2008-04-25 01:59:09 +0000910 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Benjamin Petersone41251e2008-04-25 01:59:09 +0000912 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +0000913
Benjamin Petersone41251e2008-04-25 01:59:09 +0000914 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
Benjamin Petersone41251e2008-04-25 01:59:09 +0000916 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000917
Benjamin Petersone41251e2008-04-25 01:59:09 +0000918 Creates a new Decimal instance from *num* but using *self* as
919 context. Unlike the :class:`Decimal` constructor, the context precision,
920 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
Benjamin Petersone41251e2008-04-25 01:59:09 +0000922 This is useful because constants are often given to a greater precision
923 than is needed by the application. Another benefit is that rounding
924 immediately eliminates unintended effects from digits beyond the current
925 precision. In the following example, using unrounded inputs means that
926 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +0000927
Benjamin Petersone41251e2008-04-25 01:59:09 +0000928 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Benjamin Petersone41251e2008-04-25 01:59:09 +0000930 >>> getcontext().prec = 3
931 >>> Decimal('3.4445') + Decimal('1.0023')
932 Decimal('4.45')
933 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
934 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Benjamin Petersone41251e2008-04-25 01:59:09 +0000936 This method implements the to-number operation of the IBM specification.
937 If the argument is a string, no leading or trailing whitespace is
938 permitted.
939
Georg Brandl45f53372009-01-03 21:15:20 +0000940 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000941
942 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +0000943 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +0000944 the context precision, rounding method, flags, and traps are applied to
945 the conversion.
946
947 .. doctest::
948
Georg Brandl45f53372009-01-03 21:15:20 +0000949 >>> context = Context(prec=5, rounding=ROUND_DOWN)
950 >>> context.create_decimal_from_float(math.pi)
951 Decimal('3.1415')
952 >>> context = Context(prec=5, traps=[Inexact])
953 >>> context.create_decimal_from_float(math.pi)
954 Traceback (most recent call last):
955 ...
956 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +0000957
Georg Brandl45f53372009-01-03 21:15:20 +0000958 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000959
Benjamin Petersone41251e2008-04-25 01:59:09 +0000960 .. method:: Etiny()
961
962 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
963 value for subnormal results. When underflow occurs, the exponent is set
964 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966
Benjamin Petersone41251e2008-04-25 01:59:09 +0000967 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +0000968
Benjamin Petersone41251e2008-04-25 01:59:09 +0000969 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Benjamin Petersone41251e2008-04-25 01:59:09 +0000971 The usual approach to working with decimals is to create :class:`Decimal`
972 instances and then apply arithmetic operations which take place within the
973 current context for the active thread. An alternative approach is to use
974 context methods for calculating within a specific context. The methods are
975 similar to those for the :class:`Decimal` class and are only briefly
976 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +0000977
978
Benjamin Petersone41251e2008-04-25 01:59:09 +0000979 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Benjamin Petersone41251e2008-04-25 01:59:09 +0000981 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +0000982
983
Benjamin Petersone41251e2008-04-25 01:59:09 +0000984 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Benjamin Petersone41251e2008-04-25 01:59:09 +0000986 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988
Facundo Batista789bdf02008-06-21 17:29:41 +0000989 .. method:: canonical(x)
990
991 Returns the same Decimal object *x*.
992
993
994 .. method:: compare(x, y)
995
996 Compares *x* and *y* numerically.
997
998
999 .. method:: compare_signal(x, y)
1000
1001 Compares the values of the two operands numerically.
1002
1003
1004 .. method:: compare_total(x, y)
1005
1006 Compares two operands using their abstract representation.
1007
1008
1009 .. method:: compare_total_mag(x, y)
1010
1011 Compares two operands using their abstract representation, ignoring sign.
1012
1013
1014 .. method:: copy_abs(x)
1015
1016 Returns a copy of *x* with the sign set to 0.
1017
1018
1019 .. method:: copy_negate(x)
1020
1021 Returns a copy of *x* with the sign inverted.
1022
1023
1024 .. method:: copy_sign(x, y)
1025
1026 Copies the sign from *y* to *x*.
1027
1028
Benjamin Petersone41251e2008-04-25 01:59:09 +00001029 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Benjamin Petersone41251e2008-04-25 01:59:09 +00001031 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001032
1033
Benjamin Petersone41251e2008-04-25 01:59:09 +00001034 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035
Benjamin Petersone41251e2008-04-25 01:59:09 +00001036 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037
1038
Benjamin Petersone41251e2008-04-25 01:59:09 +00001039 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Benjamin Petersone41251e2008-04-25 01:59:09 +00001041 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043
Facundo Batista789bdf02008-06-21 17:29:41 +00001044 .. method:: exp(x)
1045
1046 Returns `e ** x`.
1047
1048
1049 .. method:: fma(x, y, z)
1050
1051 Returns *x* multiplied by *y*, plus *z*.
1052
1053
1054 .. method:: is_canonical(x)
1055
1056 Returns True if *x* is canonical; otherwise returns False.
1057
1058
1059 .. method:: is_finite(x)
1060
1061 Returns True if *x* is finite; otherwise returns False.
1062
1063
1064 .. method:: is_infinite(x)
1065
1066 Returns True if *x* is infinite; otherwise returns False.
1067
1068
1069 .. method:: is_nan(x)
1070
1071 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1072
1073
1074 .. method:: is_normal(x)
1075
1076 Returns True if *x* is a normal number; otherwise returns False.
1077
1078
1079 .. method:: is_qnan(x)
1080
1081 Returns True if *x* is a quiet NaN; otherwise returns False.
1082
1083
1084 .. method:: is_signed(x)
1085
1086 Returns True if *x* is negative; otherwise returns False.
1087
1088
1089 .. method:: is_snan(x)
1090
1091 Returns True if *x* is a signaling NaN; otherwise returns False.
1092
1093
1094 .. method:: is_subnormal(x)
1095
1096 Returns True if *x* is subnormal; otherwise returns False.
1097
1098
1099 .. method:: is_zero(x)
1100
1101 Returns True if *x* is a zero; otherwise returns False.
1102
1103
1104 .. method:: ln(x)
1105
1106 Returns the natural (base e) logarithm of *x*.
1107
1108
1109 .. method:: log10(x)
1110
1111 Returns the base 10 logarithm of *x*.
1112
1113
1114 .. method:: logb(x)
1115
1116 Returns the exponent of the magnitude of the operand's MSD.
1117
1118
1119 .. method:: logical_and(x, y)
1120
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001121 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001122
1123
1124 .. method:: logical_invert(x)
1125
1126 Invert all the digits in *x*.
1127
1128
1129 .. method:: logical_or(x, y)
1130
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001131 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001132
1133
1134 .. method:: logical_xor(x, y)
1135
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001136 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001137
1138
1139 .. method:: max(x, y)
1140
1141 Compares two values numerically and returns the maximum.
1142
1143
1144 .. method:: max_mag(x, y)
1145
1146 Compares the values numerically with their sign ignored.
1147
1148
1149 .. method:: min(x, y)
1150
1151 Compares two values numerically and returns the minimum.
1152
1153
1154 .. method:: min_mag(x, y)
1155
1156 Compares the values numerically with their sign ignored.
1157
1158
Benjamin Petersone41251e2008-04-25 01:59:09 +00001159 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001160
Benjamin Petersone41251e2008-04-25 01:59:09 +00001161 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001162
1163
Benjamin Petersone41251e2008-04-25 01:59:09 +00001164 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001165
Benjamin Petersone41251e2008-04-25 01:59:09 +00001166 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001167
1168
Facundo Batista789bdf02008-06-21 17:29:41 +00001169 .. method:: next_minus(x)
1170
1171 Returns the largest representable number smaller than *x*.
1172
1173
1174 .. method:: next_plus(x)
1175
1176 Returns the smallest representable number larger than *x*.
1177
1178
1179 .. method:: next_toward(x, y)
1180
1181 Returns the number closest to *x*, in direction towards *y*.
1182
1183
1184 .. method:: normalize(x)
1185
1186 Reduces *x* to its simplest form.
1187
1188
1189 .. method:: number_class(x)
1190
1191 Returns an indication of the class of *x*.
1192
1193
Benjamin Petersone41251e2008-04-25 01:59:09 +00001194 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001195
Benjamin Petersone41251e2008-04-25 01:59:09 +00001196 Plus corresponds to the unary prefix plus operator in Python. This
1197 operation applies the context precision and rounding, so it is *not* an
1198 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001199
1200
Benjamin Petersone41251e2008-04-25 01:59:09 +00001201 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +00001202
Benjamin Petersone41251e2008-04-25 01:59:09 +00001203 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Benjamin Petersone41251e2008-04-25 01:59:09 +00001205 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1206 must be integral. The result will be inexact unless ``y`` is integral and
1207 the result is finite and can be expressed exactly in 'precision' digits.
1208 The result should always be correctly rounded, using the rounding mode of
1209 the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
Benjamin Petersone41251e2008-04-25 01:59:09 +00001211 With three arguments, compute ``(x**y) % modulo``. For the three argument
1212 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Benjamin Petersone41251e2008-04-25 01:59:09 +00001214 - all three arguments must be integral
1215 - ``y`` must be nonnegative
1216 - at least one of ``x`` or ``y`` must be nonzero
1217 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001218
Mark Dickinsonf9793a32010-02-22 15:42:18 +00001219 The value resulting from ``Context.power(x, y, modulo)`` is
1220 equal to the value that would be obtained by computing ``(x**y)
1221 % modulo`` with unbounded precision, but is computed more
1222 efficiently. The exponent of the result is zero, regardless of
1223 the exponents of ``x``, ``y`` and ``modulo``. The result is
1224 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Facundo Batista789bdf02008-06-21 17:29:41 +00001226
1227 .. method:: quantize(x, y)
1228
1229 Returns a value equal to *x* (rounded), having the exponent of *y*.
1230
1231
1232 .. method:: radix()
1233
1234 Just returns 10, as this is Decimal, :)
1235
1236
Benjamin Petersone41251e2008-04-25 01:59:09 +00001237 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001238
Benjamin Petersone41251e2008-04-25 01:59:09 +00001239 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001240
Benjamin Petersone41251e2008-04-25 01:59:09 +00001241 The sign of the result, if non-zero, is the same as that of the original
1242 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001243
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001244
Facundo Batista789bdf02008-06-21 17:29:41 +00001245 .. method:: remainder_near(x, y)
1246
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001247 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1248 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001249
1250
1251 .. method:: rotate(x, y)
1252
1253 Returns a rotated copy of *x*, *y* times.
1254
1255
1256 .. method:: same_quantum(x, y)
1257
1258 Returns True if the two operands have the same exponent.
1259
1260
1261 .. method:: scaleb (x, y)
1262
1263 Returns the first operand after adding the second value its exp.
1264
1265
1266 .. method:: shift(x, y)
1267
1268 Returns a shifted copy of *x*, *y* times.
1269
1270
1271 .. method:: sqrt(x)
1272
1273 Square root of a non-negative number to context precision.
1274
1275
Benjamin Petersone41251e2008-04-25 01:59:09 +00001276 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001277
Benjamin Petersone41251e2008-04-25 01:59:09 +00001278 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001279
Facundo Batista789bdf02008-06-21 17:29:41 +00001280
1281 .. method:: to_eng_string(x)
1282
1283 Converts a number to a string, using scientific notation.
1284
1285
1286 .. method:: to_integral_exact(x)
1287
1288 Rounds to an integer.
1289
1290
Benjamin Petersone41251e2008-04-25 01:59:09 +00001291 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001292
Benjamin Petersone41251e2008-04-25 01:59:09 +00001293 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001294
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001295.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001296
1297
1298.. _decimal-signals:
1299
1300Signals
1301-------
1302
1303Signals represent conditions that arise during computation. Each corresponds to
1304one context flag and one context trap enabler.
1305
Raymond Hettinger86173da2008-02-01 20:38:12 +00001306The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001307computation, flags may be checked for informational purposes (for instance, to
1308determine whether a computation was exact). After checking the flags, be sure to
1309clear all flags before starting the next computation.
1310
1311If the context's trap enabler is set for the signal, then the condition causes a
1312Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1313is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1314condition.
1315
1316
1317.. class:: Clamped
1318
1319 Altered an exponent to fit representation constraints.
1320
1321 Typically, clamping occurs when an exponent falls outside the context's
1322 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325
1326.. class:: DecimalException
1327
1328 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1329
1330
1331.. class:: DivisionByZero
1332
1333 Signals the division of a non-infinite number by zero.
1334
1335 Can occur with division, modulo division, or when raising a number to a negative
1336 power. If this signal is not trapped, returns :const:`Infinity` or
1337 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1338
1339
1340.. class:: Inexact
1341
1342 Indicates that rounding occurred and the result is not exact.
1343
1344 Signals when non-zero digits were discarded during rounding. The rounded result
1345 is returned. The signal flag or trap is used to detect when results are
1346 inexact.
1347
1348
1349.. class:: InvalidOperation
1350
1351 An invalid operation was performed.
1352
1353 Indicates that an operation was requested that does not make sense. If not
1354 trapped, returns :const:`NaN`. Possible causes include::
1355
1356 Infinity - Infinity
1357 0 * Infinity
1358 Infinity / Infinity
1359 x % 0
1360 Infinity % x
1361 x._rescale( non-integer )
1362 sqrt(-x) and x > 0
1363 0 ** 0
1364 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001365 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001366
1367
1368.. class:: Overflow
1369
1370 Numerical overflow.
1371
Benjamin Petersone41251e2008-04-25 01:59:09 +00001372 Indicates the exponent is larger than :attr:`Emax` after rounding has
1373 occurred. If not trapped, the result depends on the rounding mode, either
1374 pulling inward to the largest representable finite number or rounding outward
1375 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1376 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001377
1378
1379.. class:: Rounded
1380
1381 Rounding occurred though possibly no information was lost.
1382
Benjamin Petersone41251e2008-04-25 01:59:09 +00001383 Signaled whenever rounding discards digits; even if those digits are zero
1384 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1385 the result unchanged. This signal is used to detect loss of significant
1386 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001387
1388
1389.. class:: Subnormal
1390
1391 Exponent was lower than :attr:`Emin` prior to rounding.
1392
Benjamin Petersone41251e2008-04-25 01:59:09 +00001393 Occurs when an operation result is subnormal (the exponent is too small). If
1394 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396
1397.. class:: Underflow
1398
1399 Numerical underflow with result rounded to zero.
1400
1401 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1402 and :class:`Subnormal` are also signaled.
1403
1404The following table summarizes the hierarchy of signals::
1405
1406 exceptions.ArithmeticError(exceptions.Exception)
1407 DecimalException
1408 Clamped
1409 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1410 Inexact
1411 Overflow(Inexact, Rounded)
1412 Underflow(Inexact, Rounded, Subnormal)
1413 InvalidOperation
1414 Rounded
1415 Subnormal
1416
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001417.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419
1420.. _decimal-notes:
1421
1422Floating Point Notes
1423--------------------
1424
1425
1426Mitigating round-off error with increased precision
1427^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1428
1429The use of decimal floating point eliminates decimal representation error
1430(making it possible to represent :const:`0.1` exactly); however, some operations
1431can still incur round-off error when non-zero digits exceed the fixed precision.
1432
1433The effects of round-off error can be amplified by the addition or subtraction
1434of nearly offsetting quantities resulting in loss of significance. Knuth
1435provides two instructive examples where rounded floating point arithmetic with
1436insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001437properties of addition:
1438
1439.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441 # Examples from Seminumerical Algorithms, Section 4.2.2.
1442 >>> from decimal import Decimal, getcontext
1443 >>> getcontext().prec = 8
1444
1445 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1446 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001447 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001448 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001449 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001450
1451 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1452 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001453 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001454 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001455 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001456
1457The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001458expanding the precision sufficiently to avoid loss of significance:
1459
1460.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001461
1462 >>> getcontext().prec = 20
1463 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1464 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001465 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001466 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001467 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001468 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001469 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1470 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001471 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001472 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001473 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001474
1475
1476Special values
1477^^^^^^^^^^^^^^
1478
1479The number system for the :mod:`decimal` module provides special values
1480including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001482
1483Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1484they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1485not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1486can result from rounding beyond the limits of the largest representable number.
1487
1488The infinities are signed (affine) and can be used in arithmetic operations
1489where they get treated as very large, indeterminate numbers. For instance,
1490adding a constant to infinity gives another infinite result.
1491
1492Some operations are indeterminate and return :const:`NaN`, or if the
1493:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1494``0/0`` returns :const:`NaN` which means "not a number". This variety of
1495:const:`NaN` is quiet and, once created, will flow through other computations
1496always resulting in another :const:`NaN`. This behavior can be useful for a
1497series of computations that occasionally have missing inputs --- it allows the
1498calculation to proceed while flagging specific results as invalid.
1499
1500A variant is :const:`sNaN` which signals rather than remaining quiet after every
1501operation. This is a useful return value when an invalid result needs to
1502interrupt a calculation for special handling.
1503
Christian Heimes77c02eb2008-02-09 02:18:51 +00001504The behavior of Python's comparison operators can be a little surprising where a
1505:const:`NaN` is involved. A test for equality where one of the operands is a
1506quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1507``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1508:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1509``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1510if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001511not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001512specify the behavior of direct comparisons; these rules for comparisons
1513involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1514section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1515and :meth:`compare-signal` methods instead.
1516
Georg Brandl116aa622007-08-15 14:28:22 +00001517The signed zeros can result from calculations that underflow. They keep the sign
1518that would have resulted if the calculation had been carried out to greater
1519precision. Since their magnitude is zero, both positive and negative zeros are
1520treated as equal and their sign is informational.
1521
1522In addition to the two signed zeros which are distinct yet equal, there are
1523various representations of zero with differing precisions yet equivalent in
1524value. This takes a bit of getting used to. For an eye accustomed to
1525normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001526the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001527
1528 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001529 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001530
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001531.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001532
1533
1534.. _decimal-threads:
1535
1536Working with threads
1537--------------------
1538
1539The :func:`getcontext` function accesses a different :class:`Context` object for
1540each thread. Having separate thread contexts means that threads may make
1541changes (such as ``getcontext.prec=10``) without interfering with other threads.
1542
1543Likewise, the :func:`setcontext` function automatically assigns its target to
1544the current thread.
1545
1546If :func:`setcontext` has not been called before :func:`getcontext`, then
1547:func:`getcontext` will automatically create a new context for use in the
1548current thread.
1549
1550The new context is copied from a prototype context called *DefaultContext*. To
1551control the defaults so that each thread will use the same values throughout the
1552application, directly modify the *DefaultContext* object. This should be done
1553*before* any threads are started so that there won't be a race condition between
1554threads calling :func:`getcontext`. For example::
1555
1556 # Set applicationwide defaults for all threads about to be launched
1557 DefaultContext.prec = 12
1558 DefaultContext.rounding = ROUND_DOWN
1559 DefaultContext.traps = ExtendedContext.traps.copy()
1560 DefaultContext.traps[InvalidOperation] = 1
1561 setcontext(DefaultContext)
1562
1563 # Afterwards, the threads can be started
1564 t1.start()
1565 t2.start()
1566 t3.start()
1567 . . .
1568
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001569.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001570
1571
1572.. _decimal-recipes:
1573
1574Recipes
1575-------
1576
1577Here are a few recipes that serve as utility functions and that demonstrate ways
1578to work with the :class:`Decimal` class::
1579
1580 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1581 pos='', neg='-', trailneg=''):
1582 """Convert Decimal to a money formatted string.
1583
1584 places: required number of places after the decimal point
1585 curr: optional currency symbol before the sign (may be blank)
1586 sep: optional grouping separator (comma, period, space, or blank)
1587 dp: decimal point indicator (comma or period)
1588 only specify as blank when places is zero
1589 pos: optional sign for positive numbers: '+', space or blank
1590 neg: optional sign for negative numbers: '-', '(', space or blank
1591 trailneg:optional trailing minus indicator: '-', ')', space or blank
1592
1593 >>> d = Decimal('-1234567.8901')
1594 >>> moneyfmt(d, curr='$')
1595 '-$1,234,567.89'
1596 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1597 '1.234.568-'
1598 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1599 '($1,234,567.89)'
1600 >>> moneyfmt(Decimal(123456789), sep=' ')
1601 '123 456 789.00'
1602 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001603 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001604
1605 """
Christian Heimesa156e092008-02-16 07:38:31 +00001606 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001607 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001608 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001609 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001610 build, next = result.append, digits.pop
1611 if sign:
1612 build(trailneg)
1613 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001614 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001615 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001616 if not digits:
1617 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001618 i = 0
1619 while digits:
1620 build(next())
1621 i += 1
1622 if i == 3 and digits:
1623 i = 0
1624 build(sep)
1625 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001626 build(neg if sign else pos)
1627 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629 def pi():
1630 """Compute Pi to the current precision.
1631
Georg Brandl6911e3c2007-09-04 07:15:32 +00001632 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001633 3.141592653589793238462643383
1634
1635 """
1636 getcontext().prec += 2 # extra digits for intermediate steps
1637 three = Decimal(3) # substitute "three=3.0" for regular floats
1638 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1639 while s != lasts:
1640 lasts = s
1641 n, na = n+na, na+8
1642 d, da = d+da, da+32
1643 t = (t * n) / d
1644 s += t
1645 getcontext().prec -= 2
1646 return +s # unary plus applies the new precision
1647
1648 def exp(x):
1649 """Return e raised to the power of x. Result type matches input type.
1650
Georg Brandl6911e3c2007-09-04 07:15:32 +00001651 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001652 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001653 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001654 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001655 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001656 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001657 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001658 (7.38905609893+0j)
1659
1660 """
1661 getcontext().prec += 2
1662 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1663 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001664 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001665 i += 1
1666 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001667 num *= x
1668 s += num / fact
1669 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001670 return +s
1671
1672 def cos(x):
1673 """Return the cosine of x as measured in radians.
1674
Georg Brandl6911e3c2007-09-04 07:15:32 +00001675 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001676 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001677 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001678 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001679 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001680 (0.87758256189+0j)
1681
1682 """
1683 getcontext().prec += 2
1684 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1685 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001686 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001687 i += 2
1688 fact *= i * (i-1)
1689 num *= x * x
1690 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001691 s += num / fact * sign
1692 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001693 return +s
1694
1695 def sin(x):
1696 """Return the sine of x as measured in radians.
1697
Georg Brandl6911e3c2007-09-04 07:15:32 +00001698 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001699 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001700 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001701 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001702 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001703 (0.479425538604+0j)
1704
1705 """
1706 getcontext().prec += 2
1707 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1708 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001709 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001710 i += 2
1711 fact *= i * (i-1)
1712 num *= x * x
1713 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001714 s += num / fact * sign
1715 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001716 return +s
1717
1718
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001719.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001720
1721
1722.. _decimal-faq:
1723
1724Decimal FAQ
1725-----------
1726
1727Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1728minimize typing when using the interactive interpreter?
1729
Christian Heimesfe337bf2008-03-23 21:54:12 +00001730A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001731
1732 >>> D = decimal.Decimal
1733 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001734 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001735
1736Q. In a fixed-point application with two decimal places, some inputs have many
1737places and need to be rounded. Others are not supposed to have excess digits
1738and need to be validated. What methods should be used?
1739
1740A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001741the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001742
1743 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1744
1745 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001746 >>> Decimal('3.214').quantize(TWOPLACES)
1747 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Georg Brandl48310cd2009-01-03 21:18:54 +00001749 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001750 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1751 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001752
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001753 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001754 Traceback (most recent call last):
1755 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001756 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001757
1758Q. Once I have valid two place inputs, how do I maintain that invariant
1759throughout an application?
1760
Christian Heimesa156e092008-02-16 07:38:31 +00001761A. Some operations like addition, subtraction, and multiplication by an integer
1762will automatically preserve fixed point. Others operations, like division and
1763non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001764be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001765
1766 >>> a = Decimal('102.72') # Initial fixed-point values
1767 >>> b = Decimal('3.17')
1768 >>> a + b # Addition preserves fixed-point
1769 Decimal('105.89')
1770 >>> a - b
1771 Decimal('99.55')
1772 >>> a * 42 # So does integer multiplication
1773 Decimal('4314.24')
1774 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1775 Decimal('325.62')
1776 >>> (b / a).quantize(TWOPLACES) # And quantize division
1777 Decimal('0.03')
1778
1779In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001780to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001781
1782 >>> def mul(x, y, fp=TWOPLACES):
1783 ... return (x * y).quantize(fp)
1784 >>> def div(x, y, fp=TWOPLACES):
1785 ... return (x / y).quantize(fp)
1786
1787 >>> mul(a, b) # Automatically preserve fixed-point
1788 Decimal('325.62')
1789 >>> div(b, a)
1790 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001791
1792Q. There are many ways to express the same value. The numbers :const:`200`,
1793:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1794various precisions. Is there a way to transform them to a single recognizable
1795canonical value?
1796
1797A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001798representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001799
1800 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1801 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001802 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001803
1804Q. Some decimal values always print with exponential notation. Is there a way
1805to get a non-exponential representation?
1806
1807A. For some values, exponential notation is the only way to express the number
1808of significant places in the coefficient. For example, expressing
1809:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1810original's two-place significance.
1811
Christian Heimesa156e092008-02-16 07:38:31 +00001812If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001813remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001814value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001815
1816 >>> def remove_exponent(d):
1817 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1818
1819 >>> remove_exponent(Decimal('5E+3'))
1820 Decimal('5000')
1821
Georg Brandl116aa622007-08-15 14:28:22 +00001822Q. Is there a way to convert a regular float to a :class:`Decimal`?
1823
1824A. Yes, all binary floating point numbers can be exactly expressed as a
1825Decimal. An exact conversion may take more precision than intuition would
Christian Heimesfe337bf2008-03-23 21:54:12 +00001826suggest, so we trap :const:`Inexact` to signal a need for more precision:
1827
1828.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +00001829
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001830 def float_to_decimal(f):
1831 "Convert a floating point number to a Decimal with no loss of information"
1832 n, d = f.as_integer_ratio()
1833 with localcontext() as ctx:
1834 ctx.traps[Inexact] = True
1835 while True:
1836 try:
1837 return Decimal(n) / Decimal(d)
1838 except Inexact:
1839 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001840
Christian Heimesfe337bf2008-03-23 21:54:12 +00001841.. doctest::
1842
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001843 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001844 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001845
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001846Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001847
1848A. There is some question about whether it is advisable to mix binary and
1849decimal floating point. Also, its use requires some care to avoid the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001850representation issues associated with binary floating point:
Georg Brandl116aa622007-08-15 14:28:22 +00001851
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001852 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001853 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001854
1855Q. Within a complex calculation, how can I make sure that I haven't gotten a
1856spurious result because of insufficient precision or rounding anomalies.
1857
1858A. The decimal module makes it easy to test results. A best practice is to
1859re-run calculations using greater precision and with various rounding modes.
1860Widely differing results indicate insufficient precision, rounding mode issues,
1861ill-conditioned inputs, or a numerically unstable algorithm.
1862
1863Q. I noticed that context precision is applied to the results of operations but
1864not to the inputs. Is there anything to watch out for when mixing values of
1865different precisions?
1866
1867A. Yes. The principle is that all values are considered to be exact and so is
1868the arithmetic on those values. Only the results are rounded. The advantage
1869for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001870results can look odd if you forget that the inputs haven't been rounded:
1871
1872.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001873
1874 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001875 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001876 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001877 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001878 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001879
1880The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001881using the unary plus operation:
1882
1883.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001884
1885 >>> getcontext().prec = 3
1886 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001887 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001888
1889Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001890:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001891
1892 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001893 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001894