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