• 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 <http://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')
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')
576 Classmethod that converts a float to a decimal number, exactly.
578 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
581 `0x1.999999999999ap-4`. That equivalent value in decimal is
584 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
589 >>> Decimal.from_float(0.1)
590 Decimal('0.1000000000000000055511151231257827021181583404541015625')
591 >>> Decimal.from_float(float('nan'))
592 Decimal('NaN')
593 >>> Decimal.from_float(float('inf'))
594 Decimal('Infinity')
595 >>> Decimal.from_float(float('-inf'))
596 Decimal('-Infinity')
605 >>> Decimal(2).fma(3, 5)
606 Decimal('11')
611 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
672 :class:`Decimal` instance. If the operand is a zero then
673 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
674 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
746 converting any result equal to :const:`Decimal('0')` to
747 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
748 of an equivalence class. For example, ``Decimal('32.100')`` and
749 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
750 ``Decimal('32.1')``.
773 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
774 Decimal('1.414')
796 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
811 >>> Decimal(18).remainder_near(Decimal(10))
812 Decimal('-2')
813 >>> Decimal(25).remainder_near(Decimal(10))
814 Decimal('5')
815 >>> Decimal(35).remainder_near(Decimal(10))
816 Decimal('-5')
864 can leave up to 3 digits to the left of the decimal place and may
867 For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
896 operands*. A *logical operand* is a :class:`Decimal` instance whose
935 For example, the following code sets the current decimal precision to 42 places,
938 from decimal import localcontext
951 This is a standard context defined by the General Decimal Arithmetic
962 This is a standard context defined by the General Decimal Arithmetic
1017 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1020 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
1024 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
1032 Decimal('1.23000E+999')
1035 fixed-width decimal interchange formats specified in IEEE 754.
1039 In addition, for each of the :class:`Decimal` methods described above (with
1042 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1045 Decimal instance is accepted.
1064 Return a copy of the Decimal instance num.
1068 Creates a new Decimal instance from *num* but using *self* as
1069 context. Unlike the :class:`Decimal` constructor, the context precision,
1081 >>> Decimal('3.4445') + Decimal('1.0023')
1082 Decimal('4.45')
1083 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1084 Decimal('4.44')
1092 Creates a new Decimal instance from a float *f* but rounding using *self*
1093 as the context. Unlike the :meth:`Decimal.from_float` class method,
1101 Decimal('3.1415')
1106 decimal.Inexact: None
1120 The usual approach to working with decimals is to create :class:`Decimal`
1124 similar to those for the :class:`Decimal` class and are only briefly
1140 Returns the same Decimal object *x*.
1388 Just returns 10, as this is Decimal, :)
1440 can leave up to 3 digits to the left of the decimal place and may
1630 permitted in the :class:`~decimal.Decimal` constructor,
1631 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1634 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1635 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1668 The use of decimal floating point eliminates decimal representation error
1681 >>> from decimal import Decimal, getcontext
1684 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1686 Decimal('9.5111111')
1688 Decimal('10')
1690 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1692 Decimal('0.01')
1694 Decimal('0.0060000')
1696 The :mod:`decimal` module makes it possible to restore the identities by
1702 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1704 Decimal('9.51111111')
1706 Decimal('9.51111111')
1708 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1710 Decimal('0.0060000')
1712 Decimal('0.0060000')
1718 The number system for the :mod:`decimal` module provides special values
1722 Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1746 ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1750 not trapped. Note that the General Decimal Arithmetic specification does not
1767 >>> 1 / Decimal('Infinity')
1768 Decimal('0E-1000026')
1817 to work with the :class:`Decimal` class::
1821 """Convert Decimal to a money formatted string.
1823 places: required number of places after the decimal point
1826 dp: decimal point indicator (comma or period)
1832 >>> d = Decimal('-1234567.8901')
1839 >>> moneyfmt(Decimal(123456789), sep=' ')
1841 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1845 q = Decimal(10) ** -places # 2 places --> '0.01'
1877 three = Decimal(3) # substitute "three=3.0" for regular floats
1891 >>> print(exp(Decimal(1)))
1893 >>> print(exp(Decimal(2)))
1918 >>> print(cos(Decimal('0.5')))
1944 >>> print(sin(Decimal('0.5')))
1970 Decimal FAQ
1973 Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1978 >>> D = decimal.Decimal
1980 Decimal('4.68')
1982 Q. In a fixed-point application with two decimal places, some inputs have many
1986 A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1989 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1992 >>> Decimal('3.214').quantize(TWOPLACES)
1993 Decimal('3.21')
1996 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1997 Decimal('3.21')
1999 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
2009 non-integer multiplication, will change the number of decimal places and need to
2012 >>> a = Decimal('102.72') # Initial fixed-point values
2013 >>> b = Decimal('3.17')
2015 Decimal('105.89')
2017 Decimal('99.55')
2019 Decimal('4314.24')
2021 Decimal('325.62')
2023 Decimal('0.03')
2034 Decimal('325.62')
2036 Decimal('0.03')
2046 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
2048 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
2050 Q. Some decimal values always print with exponential notation. Is there a way
2063 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2065 >>> remove_exponent(Decimal('5E+3'))
2066 Decimal('5000')
2068 Q. Is there a way to convert a regular float to a :class:`Decimal`?
2071 Decimal though an exact conversion may take more precision than intuition would
2076 >>> Decimal(math.pi)
2077 Decimal('3.141592653589793115997963468544185161590576171875')
2082 A. The decimal module makes it easy to test results. A best practice is to
2099 >>> Decimal('3.104') + Decimal('2.104')
2100 Decimal('5.21')
2101 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
2102 Decimal('5.20')
2110 >>> +Decimal('1.23456789') # unary plus triggers rounding
2111 Decimal('1.23')
2117 Decimal('1.2345')
2122 the decimal module integrate the high speed `libmpdec
2124 arbitrary precision correctly-rounded decimal floating point arithmetic.