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
756 For example, ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both
757 normalize to the equivalent value ``Decimal('32.1')``.
785 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
786 Decimal('1.414')
808 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
823 >>> Decimal(18).remainder_near(Decimal(10))
824 Decimal('-2')
825 >>> Decimal(25).remainder_near(Decimal(10))
826 Decimal('5')
827 >>> Decimal(35).remainder_near(Decimal(10))
828 Decimal('-5')
876 can leave up to 3 digits to the left of the decimal place and may
879 For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
900 Decimal numbers can be rounded using the :func:`.round` function:
908 :class:`Decimal` context. Raises :exc:`OverflowError` if *number* is an
912 and a :class:`Decimal` representing *number* rounded to the nearest
913 multiple of ``Decimal('1E-ndigits')`` is returned; in this case,
915 ``self.quantize(Decimal('1E-ndigits'))``. Returns ``Decimal('NaN')`` if
921 * if *ndigits* is positive, return *number* rounded to *ndigits* decimal
929 >>> from decimal import Decimal, getcontext, ROUND_DOWN
931 >>> round(Decimal('3.75')) # context rounding ignored
933 >>> round(Decimal('3.5')) # round-ties-to-even
935 >>> round(Decimal('3.75'), 0) # uses the context rounding
936 Decimal('3')
937 >>> round(Decimal('3.75'), 1)
938 Decimal('3.7')
939 >>> round(Decimal('3.75'), -1)
940 Decimal('0E+1')
948 The :meth:`~Decimal.logical_and`, :meth:`~Decimal.logical_invert`, :meth:`~Decimal.logical_or`,
949 and :meth:`~Decimal.logical_xor` methods expect their arguments to be *logical
950 operands*. A *logical operand* is a :class:`Decimal` instance whose
990 For example, the following code sets the current decimal precision to 42 places,
993 from decimal import localcontext
1002 from decimal import localcontext
1021 This is a standard context defined by the General Decimal Arithmetic
1032 This is a standard context defined by the General Decimal Arithmetic
1087 lowercase ``e`` is used: ``Decimal('6.02e+23')``.
1090 If set to ``1``, the exponent ``e`` of a :class:`Decimal`
1094 the :class:`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is
1102 Decimal('1.23000E+999')
1105 fixed-width decimal interchange formats specified in IEEE 754.
1109 In addition, for each of the :class:`Decimal` methods described above (with
1110 the exception of the :meth:`~Decimal.adjusted` and :meth:`~Decimal.as_tuple` methods) there is
1112 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1115 Decimal instance is accepted.
1134 Return a copy of the Decimal instance num.
1138 Creates a new Decimal instance from *num* but using *self* as
1139 context. Unlike the :class:`Decimal` constructor, the context precision,
1151 >>> Decimal('3.4445') + Decimal('1.0023')
1152 Decimal('4.45')
1153 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1154 Decimal('4.44')
1162 Creates a new Decimal instance from a float *f* but rounding using *self*
1163 as the context. Unlike the :meth:`Decimal.from_float` class method,
1171 Decimal('3.1415')
1176 decimal.Inexact: None
1190 The usual approach to working with decimals is to create :class:`Decimal`
1194 similar to those for the :class:`Decimal` class and are only briefly
1210 Returns the same Decimal object *x*.
1430 ``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if ``InvalidOperation``
1431 is not trapped, then results in ``Decimal('NaN')``.
1461 Just returns 10, as this is Decimal, :)
1513 can leave up to 3 digits to the left of the decimal place and may
1558 the --without-decimal-contextvar option <--without-decimal-contextvar>`,
1713 permitted in the :class:`~decimal.Decimal` constructor,
1714 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1717 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1718 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1751 The use of decimal floating point eliminates decimal representation error
1764 >>> from decimal import Decimal, getcontext
1767 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1769 Decimal('9.5111111')
1771 Decimal('10')
1773 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1775 Decimal('0.01')
1777 Decimal('0.0060000')
1779 The :mod:`decimal` module makes it possible to restore the identities by
1785 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1787 Decimal('9.51111111')
1789 Decimal('9.51111111')
1791 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1793 Decimal('0.0060000')
1795 Decimal('0.0060000')
1801 The number system for the :mod:`decimal` module provides special values
1805 Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1829 ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1833 not trapped. Note that the General Decimal Arithmetic specification does not
1836 section 5.7). To ensure strict standards-compliance, use the :meth:`~Decimal.compare`
1837 and :meth:`~Decimal.compare_signal` methods instead.
1850 >>> 1 / Decimal('Infinity')
1851 Decimal('0E-1000026')
1900 to work with the :class:`Decimal` class::
1904 """Convert Decimal to a money formatted string.
1906 places: required number of places after the decimal point
1909 dp: decimal point indicator (comma or period)
1915 >>> d = Decimal('-1234567.8901')
1922 >>> moneyfmt(Decimal(123456789), sep=' ')
1924 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1928 q = Decimal(10) ** -places # 2 places --> '0.01'
1960 three = Decimal(3) # substitute "three=3.0" for regular floats
1974 >>> print(exp(Decimal(1)))
1976 >>> print(exp(Decimal(2)))
2001 >>> print(cos(Decimal('0.5')))
2027 >>> print(sin(Decimal('0.5')))
2053 Decimal FAQ
2056 Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
2061 >>> D = decimal.Decimal
2063 Decimal('4.68')
2065 Q. In a fixed-point application with two decimal places, some inputs have many
2069 A. The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal places. If
2072 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
2075 >>> Decimal('3.214').quantize(TWOPLACES)
2076 Decimal('3.21')
2079 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
2080 Decimal('3.21')
2082 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
2092 non-integer multiplication, will change the number of decimal places and need to
2093 be followed-up with a :meth:`~Decimal.quantize` step:
2095 >>> a = Decimal('102.72') # Initial fixed-point values
2096 >>> b = Decimal('3.17')
2098 Decimal('105.89')
2100 Decimal('99.55')
2102 Decimal('4314.24')
2104 Decimal('325.62')
2106 Decimal('0.03')
2109 to handle the :meth:`~Decimal.quantize` step:
2118 Decimal('325.62')
2120 Decimal('0.03')
2127 A. The :meth:`~Decimal.normalize` method maps all equivalent values to a single
2130 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
2132 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
2136 A. It occurs *after* the computation. The philosophy of the decimal
2144 >>> pi = Decimal('3.1415926535') # More than 5 digits
2146 Decimal('3.1415926535')
2148 Decimal('3.1416')
2149 >>> pi - Decimal('0.00005') # Subtract unrounded numbers, then round
2150 Decimal('3.1415')
2151 >>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded
2152 Decimal('3.1416')
2154 Q. Some decimal values always print with exponential notation. Is there a way
2167 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2169 >>> remove_exponent(Decimal('5E+3'))
2170 Decimal('5000')
2172 Q. Is there a way to convert a regular float to a :class:`Decimal`?
2175 Decimal though an exact conversion may take more precision than intuition would
2180 >>> Decimal(math.pi)
2181 Decimal('3.141592653589793115997963468544185161590576171875')
2186 A. The decimal module makes it easy to test results. A best practice is to
2203 >>> Decimal('3.104') + Decimal('2.104')
2204 Decimal('5.21')
2205 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
2206 Decimal('5.20')
2214 >>> +Decimal('1.23456789') # unary plus triggers rounding
2215 Decimal('1.23')
2221 Decimal('1.2345')
2226 the decimal module integrate the high speed `libmpdec
2228 arbitrary precision correctly rounded decimal floating-point arithmetic [#]_.
2243 >>> x = Decimal(2) ** 256
2245 Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')
2251 >>> Decimal(1) / 3
2272 >>> x = Decimal(0).logical_invert() * 9
2278 decimal.Inexact: [<class 'decimal.Inexact'>]