• Home
  • Raw
  • Download

Lines Matching full:decimal

1 :mod:`decimal` --- Decimal fixed point and floating point arithmetic
4 .. module:: decimal
5 :synopsis: Implementation of the General Decimal Arithmetic Specification.
15 **Source code:** :source:`Lib/decimal.py`
20 import decimal
22 from decimal import *
33 The :mod:`decimal` module provides support for fast correctly rounded
34 decimal floating point arithmetic. It offers several advantages over the
37 * Decimal "is based on a floating-point model which was designed with people
40 people learn at school." -- excerpt from the decimal arithmetic specification.
42 * Decimal numbers can be represented exactly. In contrast, numbers like
47 * The exactness carries over into arithmetic. In decimal floating point, ``0.1
51 reason, decimal is preferred in accounting applications which have strict
54 * The decimal module incorporates a notion of significant places so that ``1.30
61 * Unlike hardware based binary floating point, the decimal module has a user
65 >>> from decimal import *
67 >>> Decimal(1) / Decimal(7)
68 Decimal('0.142857')
70 >>> Decimal(1) / Decimal(7)
71 Decimal('0.1428571428571428571428571429')
73 * Both binary and decimal floating point are implemented in terms of published
75 capabilities, the decimal module exposes all required parts of the standard.
80 * The decimal module was designed to support "without prejudice, both exact
81 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
82 and rounded floating-point arithmetic." -- excerpt from the decimal
85 The module design is centered around three concepts: the decimal number, the
88 A decimal number is immutable. It has a sign, coefficient digits, and an
104 decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
116 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
117 Specification <https://speleotrove.com/decimal/decarith.html>`_.
131 >>> from decimal import *
139 Decimal instances can be constructed from integers, strings, floats, or tuples.
141 value of that integer or float. Decimal numbers include special values such as
146 >>> Decimal(10)
147 Decimal('10')
148 >>> Decimal('3.14')
149 Decimal('3.14')
150 >>> Decimal(3.14)
151 Decimal('3.140000000000000124344978758017532527446746826171875')
152 >>> Decimal((0, (3, 1, 4), -2))
153 Decimal('3.14')
154 >>> Decimal(str(2.0 ** 0.5))
155 Decimal('1.4142135623730951')
156 >>> Decimal(2) ** Decimal('0.5')
157 Decimal('1.414213562373095048801688724')
158 >>> Decimal('NaN')
159 Decimal('NaN')
160 >>> Decimal('-Infinity')
161 Decimal('-Infinity')
169 >>> Decimal(3.14)
172 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
173 >>> Decimal('3.5') < 3.7
176 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
177 >>> Decimal('3.5') == 3.5
182 The significance of a new Decimal is determined solely by the number of digits
189 >>> Decimal('3.0')
190 Decimal('3.0')
191 >>> Decimal('3.1415926535')
192 Decimal('3.1415926535')
193 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
194 Decimal('5.85987')
196 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
197 Decimal('5.85988')
200 a decimal raises :class:`InvalidOperation`::
202 >>> Decimal("1e9999999999999999999")
205 decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
209 Decimals interact well with much of the rest of Python. Here is a small decimal
215 >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
217 Decimal('9.25')
219 Decimal('0.03')
221 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
222 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
224 Decimal('19.29')
231 Decimal('1.3')
235 Decimal('6.70')
237 Decimal('2.5058')
239 Decimal('0.77')
241 And some mathematical functions are also available to Decimal:
244 >>> Decimal(2).sqrt()
245 Decimal('1.414213562373095048801688724')
246 >>> Decimal(1).exp()
247 Decimal('2.718281828459045235360287471')
248 >>> Decimal('10').ln()
249 Decimal('2.302585092994045684017991455')
250 >>> Decimal('10').log10()
251 Decimal('1')
253 The :meth:`~Decimal.quantize` method rounds a number to a fixed exponent. This method is
257 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
258 Decimal('7.32')
259 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
260 Decimal('8')
270 In accordance with the standard, the :mod:`decimal` module provides two ready to
280 >>> Decimal(1) / Decimal(7)
281 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
287 >>> Decimal(1) / Decimal(7)
288 Decimal('0.142857143')
289 >>> Decimal(42) / Decimal(0)
290 Decimal('Infinity')
293 >>> Decimal(42) / Decimal(0)
296 Decimal(42) / Decimal(0)
306 >>> Decimal(355) / Decimal(113)
307 Decimal('3.14159292')
322 >>> Decimal(1) / Decimal(0)
323 Decimal('Infinity')
325 >>> Decimal(1) / Decimal(0)
328 Decimal(1) / Decimal(0)
332 program. And, in many applications, data is converted to :class:`Decimal` with
340 .. _decimal-decimal:
342 Decimal objects
346 .. class:: Decimal(value="0", context=None)
348 Construct a new :class:`Decimal` object based from *value*.
350 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
351 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
352 string, it should conform to the decimal numeric string syntax after leading
359 decimal-part ::= digits '.' [digits] | ['.'] digits
363 numeric-value ::= decimal-part [exponent-part] | infinity
366 Other Unicode decimal digits are also permitted where ``digit``
367 appears above. These include decimal digits from various other
373 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
374 returns ``Decimal('1.414')``.
377 converted to its exact decimal equivalent. This conversion can often require
378 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
380 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
384 ``Decimal('3.00000')`` records all five zeros even if the context precision is
389 is raised; otherwise, the constructor returns a new Decimal with the value of
392 Once constructed, :class:`Decimal` objects are immutable.
406 Decimal floating point objects share many properties with the other built-in
408 operations and special methods apply. Likewise, decimal objects can be
413 There are some small differences between arithmetic on Decimal objects and
415 applied to Decimal objects, the sign of the result is the sign of the
420 >>> Decimal(-7) % Decimal(4)
421 Decimal('-3')
429 >>> Decimal(-7) // Decimal(4)
430 Decimal('-1')
436 Decimal objects cannot generally be combined with floats or
438 an attempt to add a :class:`Decimal` to a :class:`float`, for
440 use Python's comparison operators to compare a :class:`Decimal`
445 Mixed-type comparisons between :class:`Decimal` instances and other
448 In addition to the standard numeric properties, decimal floating point
456 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
457 position of the most significant digit with respect to the decimal point.
462 :class:`Decimal` instance as a fraction, in lowest terms and
465 >>> Decimal('-3.14').as_integer_ratio()
482 a :class:`Decimal` instance is always canonical, so this operation returns
487 Compare the values of two Decimal instances. :meth:`compare` returns a
488 Decimal instance, and if either operand is a NaN then the result is a
491 a or b is a NaN ==> Decimal('NaN')
492 a < b ==> Decimal('-1')
493 a == b ==> Decimal('0')
494 a > b ==> Decimal('1')
506 gives a total ordering on :class:`Decimal` instances. Two
507 :class:`Decimal` instances with the same numeric value but different
510 >>> Decimal('12.0').compare_total(Decimal('12'))
511 Decimal('-1')
514 result of this function is ``Decimal('0')`` if both operands have the same
515 representation, ``Decimal('-1')`` if the first operand is lower in the
516 total order than the second, and ``Decimal('1')`` if the first operand is
537 Just returns self, this method is only to comply with the Decimal
556 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
557 Decimal('-2.3')
569 >>> Decimal(1).exp()
570 Decimal('2.718281828459045235360287471')
571 >>> Decimal(321).exp()
572 Decimal('2.561702493119680037517373933E+139')
579 Note ``Decimal.from_float(0.1)`` is not the same as ``Decimal('0.1')``.
582 ``0x1.999999999999ap-4``. That equivalent value in decimal is
585 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
590 >>> Decimal.from_float(0.1)
591 Decimal('0.1000000000000000055511151231257827021181583404541015625')
592 >>> Decimal.from_float(float('nan'))
593 Decimal('NaN')
594 >>> Decimal.from_float(float('inf'))
595 Decimal('Infinity')
596 >>> Decimal.from_float(float('-inf'))
597 Decimal('-Infinity')
606 >>> Decimal(2).fma(3, 5)
607 Decimal('11')
612 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
673 :class:`Decimal` instance. If the operand is a zero then
674 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
675 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
747 converting any result equal to ``Decimal('0')`` to
748 ``Decimal('0e0')``. Used for producing canonical values for attributes
749 of an equivalence class. For example, ``Decimal('32.100')`` and
750 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
751 ``Decimal('32.1')``.
774 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
775 Decimal('1.414')
797 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
812 >>> Decimal(18).remainder_near(Decimal(10))
813 Decimal('-2')
814 >>> Decimal(25).remainder_near(Decimal(10))
815 Decimal('5')
816 >>> Decimal(35).remainder_near(Decimal(10))
817 Decimal('-5')
865 can leave up to 3 digits to the left of the decimal place and may
868 For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
895 The :meth:`~Decimal.logical_and`, :meth:`~Decimal.logical_invert`, :meth:`~Decimal.logical_or`,
896 and :meth:`~Decimal.logical_xor` methods expect their arguments to be *logical
897 operands*. A *logical operand* is a :class:`Decimal` instance whose
937 For example, the following code sets the current decimal precision to 42 places,
940 from decimal import localcontext
949 from decimal import localcontext
968 This is a standard context defined by the General Decimal Arithmetic
979 This is a standard context defined by the General Decimal Arithmetic
1034 lowercase ``e`` is used: ``Decimal('6.02e+23')``.
1037 If set to ``1``, the exponent ``e`` of a :class:`Decimal`
1041 the :class:`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is
1049 Decimal('1.23000E+999')
1052 fixed-width decimal interchange formats specified in IEEE 754.
1056 In addition, for each of the :class:`Decimal` methods described above (with
1057 the exception of the :meth:`~Decimal.adjusted` and :meth:`~Decimal.as_tuple` methods) there is
1059 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1062 Decimal instance is accepted.
1081 Return a copy of the Decimal instance num.
1085 Creates a new Decimal instance from *num* but using *self* as
1086 context. Unlike the :class:`Decimal` constructor, the context precision,
1098 >>> Decimal('3.4445') + Decimal('1.0023')
1099 Decimal('4.45')
1100 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1101 Decimal('4.44')
1109 Creates a new Decimal instance from a float *f* but rounding using *self*
1110 as the context. Unlike the :meth:`Decimal.from_float` class method,
1118 Decimal('3.1415')
1123 decimal.Inexact: None
1137 The usual approach to working with decimals is to create :class:`Decimal`
1141 similar to those for the :class:`Decimal` class and are only briefly
1157 Returns the same Decimal object *x*.
1377 ``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if ``InvalidOperation``
1378 is not trapped, then results in ``Decimal('NaN')``.
1408 Just returns 10, as this is Decimal, :)
1460 can leave up to 3 digits to the left of the decimal place and may
1505 the --without-decimal-contextvar option <--without-decimal-contextvar>`,
1660 permitted in the :class:`~decimal.Decimal` constructor,
1661 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1664 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1665 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1698 The use of decimal floating point eliminates decimal representation error
1711 >>> from decimal import Decimal, getcontext
1714 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1716 Decimal('9.5111111')
1718 Decimal('10')
1720 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1722 Decimal('0.01')
1724 Decimal('0.0060000')
1726 The :mod:`decimal` module makes it possible to restore the identities by
1732 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1734 Decimal('9.51111111')
1736 Decimal('9.51111111')
1738 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1740 Decimal('0.0060000')
1742 Decimal('0.0060000')
1748 The number system for the :mod:`decimal` module provides special values
1752 Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1776 ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1780 not trapped. Note that the General Decimal Arithmetic specification does not
1783 section 5.7). To ensure strict standards-compliance, use the :meth:`~Decimal.compare`
1784 and :meth:`~Decimal.compare_signal` methods instead.
1797 >>> 1 / Decimal('Infinity')
1798 Decimal('0E-1000026')
1847 to work with the :class:`Decimal` class::
1851 """Convert Decimal to a money formatted string.
1853 places: required number of places after the decimal point
1856 dp: decimal point indicator (comma or period)
1862 >>> d = Decimal('-1234567.8901')
1869 >>> moneyfmt(Decimal(123456789), sep=' ')
1871 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1875 q = Decimal(10) ** -places # 2 places --> '0.01'
1907 three = Decimal(3) # substitute "three=3.0" for regular floats
1921 >>> print(exp(Decimal(1)))
1923 >>> print(exp(Decimal(2)))
1948 >>> print(cos(Decimal('0.5')))
1974 >>> print(sin(Decimal('0.5')))
2000 Decimal FAQ
2003 Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
2008 >>> D = decimal.Decimal
2010 Decimal('4.68')
2012 Q. In a fixed-point application with two decimal places, some inputs have many
2016 A. The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal places. If
2019 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
2022 >>> Decimal('3.214').quantize(TWOPLACES)
2023 Decimal('3.21')
2026 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
2027 Decimal('3.21')
2029 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
2039 non-integer multiplication, will change the number of decimal places and need to
2040 be followed-up with a :meth:`~Decimal.quantize` step:
2042 >>> a = Decimal('102.72') # Initial fixed-point values
2043 >>> b = Decimal('3.17')
2045 Decimal('105.89')
2047 Decimal('99.55')
2049 Decimal('4314.24')
2051 Decimal('325.62')
2053 Decimal('0.03')
2056 to handle the :meth:`~Decimal.quantize` step:
2064 Decimal('325.62')
2066 Decimal('0.03')
2073 A. The :meth:`~Decimal.normalize` method maps all equivalent values to a single
2076 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
2078 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
2080 Q. Some decimal values always print with exponential notation. Is there a way
2093 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2095 >>> remove_exponent(Decimal('5E+3'))
2096 Decimal('5000')
2098 Q. Is there a way to convert a regular float to a :class:`Decimal`?
2101 Decimal though an exact conversion may take more precision than intuition would
2106 >>> Decimal(math.pi)
2107 Decimal('3.141592653589793115997963468544185161590576171875')
2112 A. The decimal module makes it easy to test results. A best practice is to
2129 >>> Decimal('3.104') + Decimal('2.104')
2130 Decimal('5.21')
2131 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
2132 Decimal('5.20')
2140 >>> +Decimal('1.23456789') # unary plus triggers rounding
2141 Decimal('1.23')
2147 Decimal('1.2345')
2152 the decimal module integrate the high speed `libmpdec
2154 arbitrary precision correctly rounded decimal floating point arithmetic [#]_.
2169 >>> x = Decimal(2) ** 256
2171 Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')
2177 >>> Decimal(1) / 3
2198 >>> x = Decimal(0).logical_invert() * 9
2204 decimal.Inexact: [<class 'decimal.Inexact'>]