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