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