Changeset 391 for python/trunk/Doc/library/decimal.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/decimal.rst
r2 r391 36 36 37 37 * Decimal numbers can be represented exactly. In contrast, numbers like 38 :const:`1.1` do not have an exact representation in binary floating point. End39 users typically would not expect :const:`1.1` to display as40 :const:`1.1000000000000001` as it does with binary floating point.38 :const:`1.1` and :const:`2.2` do not have exact representations in binary 39 floating point. End users typically would not expect ``1.1 + 2.2`` to display 40 as :const:`3.3000000000000003` as it does with binary floating point. 41 41 42 42 * The exactness carries over into arithmetic. In decimal floating point, ``0.1 … … 58 58 a given problem: 59 59 60 >>> from decimal import * 60 61 >>> getcontext().prec = 6 61 62 >>> Decimal(1) / Decimal(7) … … 134 135 >>> getcontext().prec = 7 # Set a new precision 135 136 136 Decimal instances can be constructed from integers, strings, or tuples. To 137 create a Decimal from a :class:`float`, first convert it to a string. This 138 serves as an explicit reminder of the details of the conversion (including 139 representation error). Decimal numbers include special values such as 137 Decimal instances can be constructed from integers, strings, floats, or tuples. 138 Construction from an integer or a float performs an exact conversion of the 139 value of that integer or float. Decimal numbers include special values such as 140 140 :const:`NaN` which stands for "Not a number", positive and negative 141 141 :const:`Infinity`, and :const:`-0`. … … 146 146 >>> Decimal('3.14') 147 147 Decimal('3.14') 148 >>> Decimal(3.14) 149 Decimal('3.140000000000000124344978758017532527446746826171875') 148 150 >>> Decimal((0, (3, 1, 4), -2)) 149 151 Decimal('3.14') … … 194 196 '1.34' 195 197 >>> float(a) 196 1.34 00000000000001198 1.34 197 199 >>> round(a, 1) # round() first converts to binary floating point 198 200 1.3 … … 315 317 Construct a new :class:`Decimal` object based from *value*. 316 318 317 *value* can be an integer, string, tuple, or another :class:`Decimal`319 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal` 318 320 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a 319 321 string, it should conform to the decimal numeric string syntax after leading … … 342 344 returns ``Decimal('1.414')``. 343 345 346 If *value* is a :class:`float`, the binary floating point value is losslessly 347 converted to its exact decimal equivalent. This conversion can often require 348 53 or more digits of precision. For example, ``Decimal(float('1.1'))`` 349 converts to 350 ``Decimal('1.100000000000000088817841970012523233890533447265625')``. 351 344 352 The *context* precision does not affect how many digits are stored. That is 345 353 determined exclusively by the number of digits in *value*. For example, … … 357 365 leading and trailing whitespace characters are permitted when 358 366 creating a Decimal instance from a string. 367 368 .. versionchanged:: 2.7 369 The argument to the constructor is now permitted to be a :class:`float` instance. 359 370 360 371 Decimal floating point objects share many properties with the other built-in … … 365 376 :class:`long`). 366 377 378 There are some small differences between arithmetic on Decimal objects and 379 arithmetic on integers and floats. When the remainder operator ``%`` is 380 applied to Decimal objects, the sign of the result is the sign of the 381 *dividend* rather than the sign of the divisor:: 382 383 >>> (-7) % 4 384 1 385 >>> Decimal(-7) % Decimal(4) 386 Decimal('-3') 387 388 The integer division operator ``//`` behaves analogously, returning the 389 integer part of the true quotient (truncating towards zero) rather than its 390 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``:: 391 392 >>> -7 // 4 393 -2 394 >>> Decimal(-7) // Decimal(4) 395 Decimal('-1') 396 397 The ``%`` and ``//`` operators implement the ``remainder`` and 398 ``divide-integer`` operations (respectively) as described in the 399 specification. 400 401 Decimal objects cannot generally be combined with floats in 402 arithmetic operations: an attempt to add a :class:`Decimal` to a 403 :class:`float`, for example, will raise a :exc:`TypeError`. 404 There's one exception to this rule: it's possible to use Python's 405 comparison operators to compare a :class:`float` instance ``x`` 406 with a :class:`Decimal` instance ``y``. Without this exception, 407 comparisons between :class:`Decimal` and :class:`float` instances 408 would follow the general rules for comparing objects of different 409 types described in the :ref:`expressions` section of the reference 410 manual, leading to confusing results. 411 412 .. versionchanged:: 2.7 413 A comparison between a :class:`float` instance ``x`` and a 414 :class:`Decimal` instance ``y`` now returns a result based on 415 the values of ``x`` and ``y``. In earlier versions ``x < y`` 416 returned the same (arbitrary) result for any :class:`Decimal` 417 instance ``x`` and any :class:`float` instance ``y``. 418 367 419 In addition to the standard numeric properties, decimal floating point 368 420 objects also have a number of specialized methods: … … 491 543 .. versionadded:: 2.6 492 544 545 .. method:: from_float(f) 546 547 Classmethod that converts a float to a decimal number, exactly. 548 549 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`. 550 Since 0.1 is not exactly representable in binary floating point, the 551 value is stored as the nearest representable value which is 552 `0x1.999999999999ap-4`. That equivalent value in decimal is 553 `0.1000000000000000055511151231257827021181583404541015625`. 554 555 .. note:: From Python 2.7 onwards, a :class:`Decimal` instance 556 can also be constructed directly from a :class:`float`. 557 558 .. doctest:: 559 560 >>> Decimal.from_float(0.1) 561 Decimal('0.1000000000000000055511151231257827021181583404541015625') 562 >>> Decimal.from_float(float('nan')) 563 Decimal('NaN') 564 >>> Decimal.from_float(float('inf')) 565 Decimal('Infinity') 566 >>> Decimal.from_float(float('-inf')) 567 Decimal('-Infinity') 568 569 .. versionadded:: 2.7 570 493 571 .. method:: fma(other, third[, context]) 494 572 … … 688 766 Normalize the number by stripping the rightmost trailing zeros and 689 767 converting any result equal to :const:`Decimal('0')` to 690 :const:`Decimal('0e0')`. Used for producing canonical values for members768 :const:`Decimal('0e0')`. Used for producing canonical values for attributes 691 769 of an equivalence class. For example, ``Decimal('32.100')`` and 692 770 ``Decimal('0.321000e+2')`` both normalize to the equivalent value … … 748 826 .. method:: remainder_near(other[, context]) 749 827 750 Compute the modulo as either a positive or negative value depending on 751 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)`` 752 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``. 753 754 If both are equally close, the one chosen will have the same sign as 755 *self*. 828 Return the remainder from dividing *self* by *other*. This differs from 829 ``self % other`` in that the sign of the remainder is chosen so as to 830 minimize its absolute value. More precisely, the return value is 831 ``self - n * other`` where ``n`` is the integer nearest to the exact 832 value of ``self / other``, and if two integers are equally near then the 833 even one is chosen. 834 835 If the result is zero then its sign will be the sign of *self*. 836 837 >>> Decimal(18).remainder_near(Decimal(10)) 838 Decimal('-2') 839 >>> Decimal(25).remainder_near(Decimal(10)) 840 Decimal('5') 841 >>> Decimal(35).remainder_near(Decimal(10)) 842 Decimal('-5') 756 843 757 844 .. method:: rotate(other[, context]) … … 890 977 s = +s # Round the final result back to the default precision 891 978 979 with localcontext(BasicContext): # temporarily use the BasicContext 980 print Decimal(1) / Decimal(7) 981 print Decimal(355) / Decimal(113) 982 892 983 New contexts can also be created using the :class:`Context` constructor 893 984 described below. In addition, the module provides three pre-made contexts: … … 922 1013 This context is used by the :class:`Context` constructor as a prototype for new 923 1014 contexts. Changing a field (such a precision) has the effect of changing the 924 default for new contexts creat ingby the :class:`Context` constructor.1015 default for new contexts created by the :class:`Context` constructor. 925 1016 926 1017 This context is most useful in multi-threaded environments. Changing one of the … … 977 1068 In addition, for each of the :class:`Decimal` methods described above (with 978 1069 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is 979 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is 980 equivalent to ``x.exp(context=C)``. 1070 a corresponding :class:`Context` method. For example, for a :class:`Context` 1071 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is 1072 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a 1073 Python integer (an instance of :class:`int` or :class:`long`) anywhere that a 1074 Decimal instance is accepted. 981 1075 982 1076 … … 1016 1110 If the argument is a string, no leading or trailing whitespace is 1017 1111 permitted. 1112 1113 .. method:: create_decimal_from_float(f) 1114 1115 Creates a new Decimal instance from a float *f* but rounding using *self* 1116 as the context. Unlike the :meth:`Decimal.from_float` class method, 1117 the context precision, rounding method, flags, and traps are applied to 1118 the conversion. 1119 1120 .. doctest:: 1121 1122 >>> context = Context(prec=5, rounding=ROUND_DOWN) 1123 >>> context.create_decimal_from_float(math.pi) 1124 Decimal('3.1415') 1125 >>> context = Context(prec=5, traps=[Inexact]) 1126 >>> context.create_decimal_from_float(math.pi) 1127 Traceback (most recent call last): 1128 ... 1129 Inexact: None 1130 1131 .. versionadded:: 2.7 1018 1132 1019 1133 .. method:: Etiny() … … 1873 1987 1874 1988 If an application does not care about tracking significance, it is easy to 1875 remove the exponent and trailing zeroes, losing significance, but keeping the 1876 value unchanged: 1877 1878 >>> def remove_exponent(d): 1879 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() 1880 1881 >>> remove_exponent(Decimal('5E+3')) 1882 Decimal('5000') 1989 remove the exponent and trailing zeros, losing significance, but keeping the 1990 value unchanged:: 1991 1992 def remove_exponent(d): 1993 '''Remove exponent and trailing zeros. 1994 1995 >>> remove_exponent(Decimal('5E+3')) 1996 Decimal('5000') 1997 1998 ''' 1999 return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() 1883 2000 1884 2001 Q. Is there a way to convert a regular float to a :class:`Decimal`? 1885 2002 1886 A. Yes, all binary floating point numbers can be exactly expressed as a 1887 Decimal. An exact conversion may take more precision than intuition would 1888 suggest, so we trap :const:`Inexact` to signal a need for more precision: 1889 1890 .. testcode:: 1891 1892 def float_to_decimal(f): 1893 "Convert a floating point number to a Decimal with no loss of information" 1894 n, d = f.as_integer_ratio() 1895 numerator, denominator = Decimal(n), Decimal(d) 1896 ctx = Context(prec=60) 1897 result = ctx.divide(numerator, denominator) 1898 while ctx.flags[Inexact]: 1899 ctx.flags[Inexact] = False 1900 ctx.prec *= 2 1901 result = ctx.divide(numerator, denominator) 1902 return result 2003 A. Yes, any binary floating point number can be exactly expressed as a 2004 Decimal though an exact conversion may take more precision than intuition would 2005 suggest: 1903 2006 1904 2007 .. doctest:: 1905 2008 1906 >>> float_to_decimal(math.pi)2009 >>> Decimal(math.pi) 1907 2010 Decimal('3.141592653589793115997963468544185161590576171875') 1908 1909 Q. Why isn't the :func:`float_to_decimal` routine included in the module?1910 1911 A. There is some question about whether it is advisable to mix binary and1912 decimal floating point. Also, its use requires some care to avoid the1913 representation issues associated with binary floating point:1914 1915 >>> float_to_decimal(1.1)1916 Decimal('1.100000000000000088817841970012523233890533447265625')1917 2011 1918 2012 Q. Within a complex calculation, how can I make sure that I haven't gotten a
Note:
See TracChangeset
for help on using the changeset viewer.