decimalDecimal fixed point and floating point arithmetic十进制定点和浮点算术

Source code: Lib/decimal.py


The decimal module provides support for fast correctly-rounded decimal floating point arithmetic. decimal模块支持快速正确舍入的十进制浮点算法。It offers several advantages over the float datatype:float数据类型相比,它有几个优点:

  • Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.“十进制”是基于一个浮点模型,该模型是为人们着想而设计的,并且必然有一个至高无上的指导原则——计算机必须提供一种与人们在学校学习的算术相同的算法。”摘自十进制算术规范。

  • Decimal numbers can be represented exactly. 十进制数可以精确表示。In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. 相反,像1.12.2这样的数字在二进制浮点中没有精确表示。End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.最终用户通常不希望1.1+2.2显示为3.30000000000000003,因为它使用二进制浮点。

  • The exactness carries over into arithmetic. 精确性传递到算术中。In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. 在十进制浮点中,0.1+0.1+0.1-0.3正好等于零。In binary floating point, the result is 5.5511151231257827e-017. 在二进制浮点中,结果为5.5511151231257827e-017While near to zero, the differences prevent reliable equality testing and differences can accumulate. 虽然接近零,但差异阻碍了可靠的平等测试,差异可能会累积。For this reason, decimal is preferred in accounting applications which have strict equality invariants.因此,在具有严格等式不变量的会计应用程序中,十进制是首选。

  • The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. 十进制模块包含有效位的概念,因此1.30+1.202.50The trailing zero is kept to indicate significance. 保留尾随零以表示重要性。This is the customary presentation for monetary applications. 这是货币应用的惯用表达方式。For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. 对于乘法,“教科书”方法使用被乘数中的所有数字。For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600.例如,1.3*1.2得到1.56,而1.30*1.20得到1.5600

  • Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:与基于硬件的二进制浮点不同,十进制模块具有用户可更改的精度(默认为28位),该精度可以根据给定问题的需要而定:

    >>> from decimal import *
    >>> getcontext().prec = 6
    >>> Decimal(1) / Decimal(7)
    Decimal('0.142857')
    >>> getcontext().prec = 28
    >>> Decimal(1) / Decimal(7)
    Decimal('0.1428571428571428571428571429')
  • Both binary and decimal floating point are implemented in terms of published standards. 二进制和十进制浮点都是根据已发布的标准实现的。While the built-in float type exposes only a modest portion of its capabilities, the decimal module exposes all required parts of the standard. 虽然内置浮点类型仅公开其功能的一小部分,但十进制模块公开了标准的所有必需部分。When needed, the programmer has full control over rounding and signal handling. 需要时,程序员可以完全控制舍入和信号处理。This includes an option to enforce exact arithmetic by using exceptions to block any inexact operations.这包括一个选项,通过使用异常阻止任何不精确的操作来强制执行精确的算术。

  • The decimal module was designed to support “without prejudice, both exact unrounded decimal arithmetic (sometimes called fixed-point arithmetic) and rounded floating-point arithmetic.” – excerpt from the decimal arithmetic specification.十进制模块旨在支持“无偏见地支持精确无舍入十进制算术(有时称为定点算术)和舍入浮点算术”摘自十进制算术规范。

The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.模块设计围绕三个概念:十进制数、算术上下文和信号。

A decimal number is immutable. 十进制数是不可变的。It has a sign, coefficient digits, and an exponent. 它有符号、系数数字和指数。To preserve significance, the coefficient digits do not truncate trailing zeros. 为了保持显著性,系数数字不会截断尾随零。Decimals also include special values such as Infinity, -Infinity, and NaN. 小数还包括特殊值,例如Infinity-InfinityNaNThe standard also differentiates -0 from +0.该标准还区分了-0+0

The context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. 算术环境是一个指定精度、舍入规则、指数限制、指示运算结果的标志以及确定信号是否被视为异常的陷阱使能器的环境。Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.舍入选项包括ROUND_CEILINGROUND_DOWNROUND_FLOORROUND_HALF_DOWNROUND_HALF_EVENROUND_HALF_UPROUND_UPROUND_05UP

Signals are groups of exceptional conditions arising during the course of computation. 信号是计算过程中出现的一组异常情况。Depending on the needs of the application, signals may be ignored, considered as informational, or treated as exceptions. 根据应用的需要,可以忽略信号、将其视为信息信号或将其视为例外情况。The signals in the decimal module are: Clamped, InvalidOperation, DivisionByZero, Inexact, Rounded, Subnormal, Overflow, Underflow and FloatOperation.十进制模块中的信号有:ClampedInvalidOperationDivisionByZeroInexactRoundedSubnormalOverflowUnderflowFloatOperation

For each signal there is a flag and a trap enabler. 每个信号都有一个标志和陷阱启用码。When a signal is encountered, its flag is set to one, then, if the trap enabler is set to one, an exception is raised. 当遇到信号时,其标志设置为1,然后,如果陷阱启用码设置为1,则会引发异常。Flags are sticky, so the user needs to reset them before monitoring a calculation.标记是粘性的,因此用户需要在监视计算之前重置它们。

See also另请参见

Quick-start Tutorial快速入门教程

The usual start to using decimals is importing the module, viewing the current context with getcontext() and, if necessary, setting new values for precision, rounding, or enabled traps:通常使用小数的开始是导入模块,使用getcontext()查看当前上下文,如有必要,为精度、舍入或启用的陷阱设置新值:

>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
InvalidOperation])
>>> getcontext().prec = 7 # Set a new precision

Decimal instances can be constructed from integers, strings, floats, or tuples. 十进制实例可以由整数、字符串、浮点或元组构造。Construction from an integer or a float performs an exact conversion of the value of that integer or float. 从整数或浮点构造执行该整数或浮点值的精确转换。Decimal numbers include special values such as NaN which stands for “Not a number”, positive and negative Infinity, and -0:十进制数包括特殊值,例如代表“非数字”的NaN、正负Infinity-0

>>> getcontext().prec = 28
>>> Decimal(10)
Decimal('10')
>>> Decimal('3.14')
Decimal('3.14')
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
>>> Decimal((0, (3, 1, 4), -2))
Decimal('3.14')
>>> Decimal(str(2.0 ** 0.5))
Decimal('1.4142135623730951')
>>> Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724')
>>> Decimal('NaN')
Decimal('NaN')
>>> Decimal('-Infinity')
Decimal('-Infinity')

If the FloatOperation signal is trapped, accidental mixing of decimals and floats in constructors or ordering comparisons raises an exception:如果FloatOperation信号被捕获,则构造函数中小数和浮点的意外混合或排序比较会引发异常:

>>> c = getcontext()
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') < 3.7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') == 3.5
True

New in version 3.3.版本3.3中新增。

The significance of a new Decimal is determined solely by the number of digits input. 新小数的意义仅由输入的位数决定。Context precision and rounding only come into play during arithmetic operations.上下文精度和舍入只在算术运算中起作用。

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

If the internal limits of the C version are exceeded, constructing a decimal raises InvalidOperation:如果超过C版本的内部限制,则构造十进制将引发InvalidOperation

>>> Decimal("1e9999999999999999999")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Changed in version 3.3.在版本3.3中更改。

Decimals interact well with much of the rest of Python. 小数与Python的许多其他部分交互良好。Here is a small decimal floating point flying circus:下面是一个小的十进制浮点飞行马戏团:

>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> sorted(data)
[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
>>> sum(data)
Decimal('19.29')
>>> a,b,c = data[:3]
>>> str(a)
'1.34'
>>> float(a)
1.34
>>> round(a, 1)
Decimal('1.3')
>>> int(a)
1
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')

And some mathematical functions are also available to Decimal:一些数学函数也可用于十进制:

>>> getcontext().prec = 28
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal('10').ln()
Decimal('2.302585092994045684017991455')
>>> Decimal('10').log10()
Decimal('1')

The quantize() method rounds a number to a fixed exponent. quantize()方法将数字舍入为固定指数。This method is useful for monetary applications that often round results to a fixed number of places:该方法适用于经常将结果舍入到固定数量位置的货币应用:

>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')

As shown above, the getcontext() function accesses the current context and allows the settings to be changed. 如上所示,getcontext()函数访问当前上下文并允许更改设置。This approach meets the needs of most applications.这种方法满足大多数应用程序的需要。

For more advanced work, it may be useful to create alternate contexts using the Context() constructor. 对于更高级的工作,使用Context()构造函数创建备用上下文可能很有用。To make an alternate active, use the setcontext() function.要激活备用项,请使用setcontext()函数。

In accordance with the standard, the decimal module provides two ready to use standard contexts, BasicContext and ExtendedContext. 根据该标准,decimal模块提供了两种现成的标准上下文,BasicContextExtendedContextThe former is especially useful for debugging because many of the traps are enabled:前者对于调试特别有用,因为启用了许多陷阱:

>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
>>> setcontext(myothercontext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857142857142857142857142857')
>>> ExtendedContext
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[])
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857143')
>>> Decimal(42) / Decimal(0)
Decimal('Infinity')

>>> setcontext(BasicContext)
>>> Decimal(42) / Decimal(0)
Traceback (most recent call last):
File "<pyshell#143>", line 1, in -toplevel-
Decimal(42) / Decimal(0)
DivisionByZero: x / 0

Contexts also have signal flags for monitoring exceptional conditions encountered during computations. 上下文还具有用于监视计算过程中遇到的异常情况的信号标志。The flags remain set until explicitly cleared, so it is best to clear the flags before each set of monitored computations by using the clear_flags() method.标志保持设置,直到显式清除,因此最好使用clear_flags()方法在每组受监视的计算之前清除标志。

>>> setcontext(ExtendedContext)
>>> getcontext().clear_flags()
>>> Decimal(355) / Decimal(113)
Decimal('3.14159292')
>>> getcontext()
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])

The flags entry shows that the rational approximation to Pi was rounded (digits beyond the context precision were thrown away) and that the result is inexact (some of the discarded digits were non-zero).flags项显示对Pi的有理近似已舍入(超出上下文精度的数字被丢弃),结果不精确(一些丢弃的数字为非零)。

Individual traps are set using the dictionary in the traps field of a context:使用上下文的traps字段中的字典设置单个陷阱:

>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(0)
Decimal('Infinity')
>>> getcontext().traps[DivisionByZero] = 1
>>> Decimal(1) / Decimal(0)
Traceback (most recent call last):
File "<pyshell#112>", line 1, in -toplevel-
Decimal(1) / Decimal(0)
DivisionByZero: x / 0

Most programs adjust the current context only once, at the beginning of the program. 大多数程序只在程序开始时调整当前上下文一次。And, in many applications, data is converted to Decimal with a single cast inside a loop. 而且,在许多应用中,数据在循环内通过单个转换转换为DecimalWith context set and decimals created, the bulk of the program manipulates the data no differently than with other Python numeric types.通过创建上下文集和小数,程序的大部分操作数据与其他Python数字类型没有什么不同。

Decimal objects十进制对象

classdecimal.Decimal(value='0', context=None)

Construct a new Decimal object based from value.基于value构造新的Decimal对象。

value can be an integer, string, tuple, float, or another Decimal object. value可以是整数、字符串、元组、float或其他Decimal对象。If no value is given, returns Decimal('0'). 如果未给定value,则返回Decimal('0')If value is a string, it should conform to the decimal numeric string syntax after leading and trailing whitespace characters, as well as underscores throughout, are removed:如果value是字符串,则在删除前导和尾随空白字符以及下划线后,它应符合十进制数字字符串语法:

sign           ::=  '+' | '-'
digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator ::= 'e' | 'E'
digits ::= digit [digit]...
decimal-part ::= digits '.' [digits] | ['.'] digits
exponent-part ::= indicator [sign] digits
infinity ::= 'Infinity' | 'Inf'
nan ::= 'NaN' [digits] | 'sNaN' [digits]
numeric-value ::= decimal-part [exponent-part] | infinity
numeric-string ::= [sign] numeric-value | [sign] nan

Other Unicode decimal digits are also permitted where digit appears above. 当数字出现在上面时,也允许使用其他Unicodedigit数字。These include decimal digits from various other alphabets (for example, Arabic-Indic and Devanāgarī digits) along with the fullwidth digits '\uff10' through '\uff19'.这些数字包括来自各种其他字母的十进制数字(例如,阿拉伯-印度和德梵那加数字),以及全宽数字'\uff10''\uff19'

If value is a tuple, it should have three components, a sign (0 for positive or 1 for negative), a tuple of digits, and an integer exponent. 如果value是一个tuple,它应该有三个分量,一个符号(0表示正,1表示负)、一个数字tuple和一个整数指数。For example, Decimal((0, (1, 4, 1, 4), -3)) returns Decimal('1.414').例如,Decimal((0, (1, 4, 1, 4), -3))返回Decimal('1.414')

If value is a float, the binary floating point value is losslessly converted to its exact decimal equivalent. 如果valuefloat,则二进制浮点值将无损地转换为精确的十进制等效值。This conversion can often require 53 or more digits of precision. 这种转换通常需要53位或更多的精度。For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').例如,Decimal(float('1.1'))转换为Decimal('1.100000000000000088817841970012523233890533447265625')

The context precision does not affect how many digits are stored. context精度不影响存储的位数。That is determined exclusively by the number of digits in value. 这完全由value中的位数决定。For example, Decimal('3.00000') records all five zeros even if the context precision is only three.例如,Decimal('3.00000')记录所有五个零,即使上下文精度只有三个。

The purpose of the context argument is determining what to do if value is a malformed string. context参数的目的是确定如果value是格式错误的字符串,该怎么办。If the context traps InvalidOperation, an exception is raised; otherwise, the constructor returns a new Decimal with the value of NaN.如果上下文陷阱InvalidOperation,则引发异常;否则,构造函数返回值为NaN的新十进制数。

Once constructed, Decimal objects are immutable.一旦构造,Decimal对象是不可变的。

Changed in version 3.2:版本3.2中更改: The argument to the constructor is now permitted to be a float instance.现在,构造函数的参数可以是float实例。

Changed in version 3.3:版本3.3中更改: float arguments raise an exception if the FloatOperation trap is set. 如果设置了FloatOperation陷阱,则float参数会引发异常。By default the trap is off.默认情况下,陷阱处于关闭状态。

Changed in version 3.6:版本3.6中更改: Underscores are allowed for grouping, as with integral and floating-point literals in code.下划线可以用于分组,就像代码中的整数和浮点文字一样。

Decimal floating point objects share many properties with the other built-in numeric types such as float and int. 十进制浮点对象与其他内置数字类型(如floatint)共享许多属性。All of the usual math operations and special methods apply. 所有常用的数学运算和特殊方法都适用。Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, sorted, and coerced to another type (such as float or int).同样,可以复制、pickle、打印十进制对象,将其用作字典键、用作集合元素、比较、排序并强制转换为另一种类型(如floatint)。

There are some small differences between arithmetic on Decimal objects and arithmetic on integers and floats. 十进制对象上的算术与整数和浮点上的算术之间有一些小的差异。When the remainder operator % is applied to Decimal objects, the sign of the result is the sign of the dividend rather than the sign of the divisor:当余数运算符%应用于十进制对象时,结果的符号是被除数的符号,而不是除数的符号:

>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')

The integer division operator // behaves analogously, returning the integer part of the true quotient (truncating towards zero) rather than its floor, so as to preserve the usual identity x == (x // y) * y + x % y:整数除法运算符//的行为类似,返回真商的整数部分(向零截断),而不是其下限,以保持通常的恒等式x == (x // y) * y + x % y

>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')

The % and // operators implement the remainder and divide-integer operations (respectively) as described in the specification.%//运算符(分别)实现规范中描述的remainder和除法整数运算。

Decimal objects cannot generally be combined with floats or instances of fractions.Fraction in arithmetic operations: an attempt to add a Decimal to a float, for example, will raise a TypeError. 在算术运算中,十进制对象通常不能与浮点或fractions.Fraction实例组合:例如,尝试将Decimal加到float会引发TypeErrorHowever, it is possible to use Python’s comparison operators to compare a Decimal instance x with another number y. 然而,可以使用Python的比较运算符将Decimal实例x与另一个数字y进行比较。This avoids confusing results when doing equality comparisons between numbers of different types.这避免了在不同类型的数字之间进行相等比较时混淆结果。

Changed in version 3.2:版本3.2中更改: Mixed-type comparisons between Decimal instances and other numeric types are now fully supported.现在完全支持Decimal实例和其他数值类型之间的混合类型比较。

In addition to the standard numeric properties, decimal floating point objects also have a number of specialized methods:除了标准的数值属性外,十进制浮点对象还有许多专门的方法:

adjusted()

Return the adjusted exponent after shifting out the coefficient’s rightmost digits until only the lead digit remains: Decimal('321e+5').adjusted() returns seven. 在移出系数最右边的数字直到只剩下前导数字后返回调整后的指数:Decimal('321e+5').adjusted()返回七。Used for determining the position of the most significant digit with respect to the decimal point.用于确定最高有效位相对于小数点的位置。

as_integer_ratio()

Return a pair (n, d) of integers that represent the given Decimal instance as a fraction, in lowest terms and with a positive denominator:返回一对(n, d)整数,以最小项和正分母表示给定的Decimal实例:

>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)

The conversion is exact. 转换是精确的。Raise OverflowError on infinities and ValueError on NaNs.在无穷大上引发OverflowerError,在NaN上引发ValueError

New in version 3.6.版本3.6中新增。

as_tuple()

Return a named tuple representation of the number: DecimalTuple(sign, digits, exponent).返回数字的命名元组表示形式:DecimalTuple(sign, digits, exponent)

canonical()

Return the canonical encoding of the argument. 返回参数的规范编码。Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged.目前,Decimal实例的编码始终是规范的,因此此操作返回其参数不变。

compare(other, context=None)

Compare the values of two Decimal instances. 比较两个十进制实例的值。compare() returns a Decimal instance, and if either operand is a NaN then the result is a NaN:compare()返回一个十进制实例,如果任一操作数是NaN,则结果是NaN:

a or b is a NaN  ==> Decimal('NaN')
a < b ==> Decimal('-1')
a == b ==> Decimal('0')
a > b ==> Decimal('1')
compare_signal(other, context=None)

This operation is identical to the compare() method, except that all NaNs signal. 该操作与compare()方法相同,不同之处在于所有NAN信号。That is, if neither operand is a signaling NaN then any quiet NaN operand is treated as though it were a signaling NaN.也就是说,如果两个操作数都不是信令NaN,则任何安静的NaN操作数都被视为信令NaN。

compare_total(other, context=None)

Compare two operands using their abstract representation rather than their numerical value. 使用两个操作数的抽象表示法而不是数值来比较它们。Similar to the compare() method, but the result gives a total ordering on Decimal instances. compare()方法类似,但结果给出了Decimal实例的总排序。Two Decimal instances with the same numeric value but different representations compare unequal in this ordering:具有相同数值但不同表示的两个Decimal实例在此顺序中比较不相等:

>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')

Quiet and signaling NaNs are also included in the total ordering. 总订单中还包括静音和信令NAN。The result of this function is Decimal('0') if both operands have the same representation, Decimal('-1') if the first operand is lower in the total order than the second, and Decimal('1') if the first operand is higher in the total order than the second operand. 如果两个操作数具有相同的表示形式,则该函数的结果为Decimal('0');如果第一个操作数的总阶数低于第二个操作数,则该函数的结果为Decimal('-1');如果第一个操作数的总阶数高于第二个操作数,则该函数的结果为Decimal('1')See the specification for details of the total order.有关总订单的详细信息,请参阅规范。

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. 此操作不受上下文影响,且安静:不更改标志,也不执行舍入。As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.作为例外,如果第二个操作数无法准确转换,C版本可能会引发InvalidOperation

compare_total_mag(other, context=None)

Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand. 使用两个操作数的抽象表示法(而不是compare_total()中的值)比较两个操作数,但忽略每个操作数的符号。x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).x.compare_total_mag(y)等价于x.copy_abs().compare_total(y.copy_abs())

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. 此操作不受上下文影响,且安静:不更改标志,也不执行舍入。As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.作为例外,如果第二个操作数无法准确转换,C版本可能会引发InvalidOperation

conjugate()

Just returns self, this method is only to comply with the Decimal Specification.仅返回self,此方法仅符合十进制规范。

copy_abs()

Return the absolute value of the argument. 返回参数的绝对值。This operation is unaffected by the context and is quiet: no flags are changed and no rounding is performed.此操作不受上下文影响,且安静:不更改标志,也不执行舍入。

copy_negate()

Return the negation of the argument. 返回参数的否定。This operation is unaffected by the context and is quiet: no flags are changed and no rounding is performed.此操作不受上下文影响,且安静:不更改标志,也不执行舍入。

copy_sign(other, context=None)

Return a copy of the first operand with the sign set to be the same as the sign of the second operand. 返回符号集与第二个操作数的符号相同的第一个操作数的副本。For example:例如:

>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. 此操作不受上下文影响,且安静:不更改标志,也不执行舍入。As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.作为例外,如果第二个操作数无法准确转换,C版本可能会引发InvalidOperation。

exp(context=None)

Return the value of the (natural) exponential function e**x at the given number. 返回给定数字处(自然)指数函数e**x的值。The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.使用ROUND_HALF_EVEN舍入模式正确舍入结果。

>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139')
from_float(f)

Classmethod that converts a float to a decimal number, exactly.将浮点数准确地转换为十进制数的Classmethod。

Note Decimal.from_float(0.1) is not the same as Decimal(‘0.1’). 注:Decimal.from_float(0.1)Decimal(‘0.1’)不同。Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. 由于0.1不能用二进制浮点精确表示,因此该值存储为最接近的可表示值,即0x1.999999999999ap-4That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625.十进制的等价值为0.1000000000000000055511151231257827021181583404541015625

Note笔记

From Python 3.2 onwards, a Decimal instance can also be constructed directly from a float.从Python 3.2开始,还可以直接从float构造Decimal实例。

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')

New in version 3.1.版本3.1中新增。

fma(other, third, context=None)

Fused multiply-add. 融合乘法加法。Return self*other+third with no rounding of the intermediate product self*other.返回self*other+third,中间产品self*other不四舍五入。

>>> Decimal(2).fma(3, 5)
Decimal('11')
is_canonical()

Return True if the argument is canonical and False otherwise. 如果参数是规范的,则返回True,否则返回FalseCurrently, a Decimal instance is always canonical, so this operation always returns True.目前,Decimal实例始终是规范的,因此此操作始终返回True

is_finite()

Return True if the argument is a finite number, and False if the argument is an infinity or a NaN.如果参数为有限数,则返回True;如果参数为无穷大或NaN,则返回False

is_infinite()

Return True if the argument is either positive or negative infinity and False otherwise.如果参数为正无穷大或负无穷大,则返回True,否则返回False

is_nan()

Return True if the argument is a (quiet or signaling) NaN and False otherwise.如果参数是(安静或信号)NaN,则返回True,否则返回False

is_normal(context=None)

Return True if the argument is a normal finite number. 如果参数是normal有限数,则返回TrueReturn False if the argument is zero, subnormal, infinite or a NaN.如果参数为零、subnormal、无限或NaN,则返回False

is_qnan()

Return True if the argument is a quiet NaN, and False otherwise.如果参数是安静的NaN,则返回True,否则返回False

is_signed()

Return True if the argument has a negative sign and False otherwise. 如果参数有负号,则返回True,否则返回FalseNote that zeros and NaNs can both carry signs.注意,零和nan都可以携带符号。

is_snan()

Return True if the argument is a signaling NaN and False otherwise.如果参数是信号NaN,则返回True,否则返回False

is_subnormal(context=None)

Return True if the argument is subnormal, and False otherwise.如果参数低于正常值,则返回True,否则返回False

is_zero()

Return True if the argument is a (positive or negative) zero and False otherwise.如果参数为(正或负)零,则返回True,否则返回False

ln(context=None)

Return the natural (base e) logarithm of the operand. 返回操作数的自然对数(以e为底)。The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.使用ROUND_HALF_EVEN舍入模式正确舍入结果。

log10(context=None)

Return the base ten logarithm of the operand. 返回操作数的以十为底的对数。The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.使用ROUND_HALF_EVEN舍入模式正确舍入结果。

logb(context=None)

For a nonzero number, return the adjusted exponent of its operand as a Decimal instance. 对于非零数,将其操作数的调整后指数作为Decimal实例返回。If the operand is a zero then Decimal('-Infinity') is returned and the DivisionByZero flag is raised. 如果操作数为零,则返回Decimal('-Infinity'),并提升DivisionByZero标志。If the operand is an infinity then Decimal('Infinity') is returned.如果操作数是无穷大,则返回Decimal('Infinity')

logical_and(other, context=None)

logical_and() is a logical operation which takes two logical operands (see Logical operands). logical_and()是采用两个逻辑操作数的逻辑运算(请参见逻辑操作数)。The result is the digit-wise and of the two operands.结果是两个操作数的数字and

logical_invert(context=None)

logical_invert() is a logical operation. 是一种逻辑操作。The result is the digit-wise inversion of the operand.结果是操作数的逐位求逆。

logical_or(other, context=None)

logical_or() is a logical operation which takes two logical operands (see Logical operands). 是采用两个逻辑操作数的逻辑运算(请参见逻辑操作数)。The result is the digit-wise or of the two operands.结果是两个操作数的数字or

logical_xor(other, context=None)

logical_xor() is a logical operation which takes two logical operands (see Logical operands). 是采用两个逻辑操作数的逻辑运算(请参见逻辑操作数)。The result is the digit-wise exclusive or of the two operands.结果是两个操作数的数字异或。

max(other, context=None)

Like max(self, other) except that the context rounding rule is applied before returning and that NaN values are either signaled or ignored (depending on the context and whether they are signaling or quiet).max(self, other)类似,不同的是在返回之前应用了上下文舍入规则,并且NaN值要么是有信号的,要么被忽略(取决于上下文以及它们是有信号的还是无信号的)。

max_mag(other, context=None)

Similar to the max() method, but the comparison is done using the absolute values of the operands.max()方法类似,但比较是使用操作数的绝对值进行的。

min(other, context=None)

Like min(self, other) except that the context rounding rule is applied before returning and that NaN values are either signaled or ignored (depending on the context and whether they are signaling or quiet).min(self, other)类似,不同的是在返回之前应用了上下文舍入规则,并且NaN值要么被信号传递,要么被忽略(取决于上下文以及它们是信号传递还是静默)。

min_mag(other, context=None)

Similar to the min() method, but the comparison is done using the absolute values of the operands.min()方法类似,但比较是使用操作数的绝对值进行的。

next_minus(context=None)

Return the largest number representable in the given context (or in the current thread’s context if no context is given) that is smaller than the given operand.返回在给定上下文(如果没有给定上下文,则在当前线程的上下文中)中可表示的小于给定操作数的最大数。

next_plus(context=None)

Return the smallest number representable in the given context (or in the current thread’s context if no context is given) that is larger than the given operand.返回在给定上下文中(或在当前线程的上下文中,如果没有给定上下文),可表示的大于给定操作数的最小数。

next_toward(other, context=None)

If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. 如果两个操作数不相等,则返回在第二个操作数方向上最接近第一个操作数的数字。If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.如果两个操作数在数字上相等,则返回第一个操作数的副本,其符号集与第二个操作数的符号相同。

normalize(context=None)

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0'). 通过去掉最右边的尾随零,并将等于Decimal('0')的任何结果转换为Decimal('0e0')来规范化数字。Used for producing canonical values for attributes of an equivalence class. 用于为等价类的属性生成规范值。For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent value Decimal('32.1').例如,Decimal('32.100')Decimal('0.321000e+2')都标准化为等效值Decimal('32.1')

number_class(context=None)

Return a string describing the class of the operand. 返回描述操作数class的字符串。The returned value is one of the following ten strings.返回值是以下十个字符串之一。

  • "-Infinity", indicating that the operand is negative infinity.,表示操作数为负无穷大。

  • "-Normal", indicating that the operand is a negative normal number.,表示操作数为负正态数。

  • "-Subnormal", indicating that the operand is negative and subnormal.,表示操作数为负且低于正常值。

  • "-Zero", indicating that the operand is a negative zero.,表示操作数为负零。

  • "+Zero", indicating that the operand is a positive zero.,表示操作数为正零。

  • "+Subnormal", indicating that the operand is positive and subnormal.,表示操作数为正且低于正常值。

  • "+Normal", indicating that the operand is a positive normal number.,表示操作数是正正整数。

  • "+Infinity", indicating that the operand is positive infinity.,表示操作数为正无穷大。

  • "NaN", indicating that the operand is a quiet NaN (Not a Number).,表示操作数是静态NaN(不是数字)。

  • "sNaN", indicating that the operand is a signaling NaN.,表示操作数是信号NaN。

quantize(exp, rounding=None, context=None)

Return a value equal to the first operand after rounding and having the exponent of the second operand.返回一个值,该值等于舍入后的第一个操作数,并具有第二个操作数的指数。

>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')

Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. 与其他操作不同,如果量化操作后系数的长度大于精度,则发出InvalidOperation的信号。This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.这保证了,除非存在错误条件,否则量化指数始终等于右侧操作数的指数。

Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.与其他操作不同的是,即使结果低于正常值且不精确,也从不量化下溢信号。

If the exponent of the second operand is larger than that of the first then rounding may be necessary. 如果第二个操作数的指数大于第一个操作数的指数,则可能需要舍入。In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given the rounding mode of the current thread’s context is used.在这种情况下,舍入模式由rounding参数(如果给定)决定,否则由给定的context参数决定;如果两个参数都没有给定,则使用当前线程上下文的舍入模式。

An error is returned whenever the resulting exponent is greater than Emax or less than Etiny.只要结果指数大于Emax或小于Etiny,就会返回错误。

radix()

Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. 返回Decimal(10)Decimal类执行其所有算术的基数(base)。Included for compatibility with the specification.包括以与规范兼容。

remainder_near(other, context=None)

Return the remainder from dividing self by other. 返回self除以other所得的余数。This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. 这与self%other的不同之处在于,选择余数的符号是为了最小化其绝对值。More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and if two integers are equally near then the even one is chosen.更准确地说,返回值是self-n*other,其中n是最接近self/other精确值的整数,如果两个整数相等,则选择偶数。

If the result is zero then its sign will be the sign of self.如果结果为零,则其符号将是self的符号。

>>> Decimal(18).remainder_near(Decimal(10))
Decimal('-2')
>>> Decimal(25).remainder_near(Decimal(10))
Decimal('5')
>>> Decimal(35).remainder_near(Decimal(10))
Decimal('-5')
rotate(other, context=None)

Return the result of rotating the digits of the first operand by an amount specified by the second operand. 返回将第一个操作数的位数旋转第二个操作数指定的量的结果。The second operand must be an integer in the range -precision through precision. 第二个操作数必须是精度到精度范围内的整数。The absolute value of the second operand gives the number of places to rotate. 第二个操作数的绝对值表示要旋转的位置数。If the second operand is positive then rotation is to the left; otherwise rotation is to the right. 如果第二个操作数为正,则旋转方向为左;否则将向右旋转。The coefficient of the first operand is padded on the left with zeros to length precision if necessary. 如有必要,第一个操作数的系数在左侧用零填充到长度精度。The sign and exponent of the first operand are unchanged.第一个操作数的符号和指数不变。

same_quantum(other, context=None)

Test whether self and other have the same exponent or whether both are NaN.测试self和other的指数是否相同,或者两者是否都是NaN

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. 此操作不受上下文影响,且安静:不更改标志,也不执行舍入。As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.作为例外,如果第二个操作数无法准确转换,C版本可能会引发InvalidOperation

scaleb(other, context=None)

Return the first operand with exponent adjusted by the second. 返回指数由第二个操作数调整的第一个操作数。Equivalently, return the first operand multiplied by 10**other. 等价地,返回第一个操作数乘以10**otherThe second operand must be an integer.第二个操作数必须是整数。

shift(other, context=None)

Return the result of shifting the digits of the first operand by an amount specified by the second operand. 返回将第一个操作数的位数移位第二个操作数指定的量的结果。The second operand must be an integer in the range -precision through precision. 第二个操作数必须是精度到精度范围内的整数。The absolute value of the second operand gives the number of places to shift. 第二个操作数的绝对值表示要移位的位数。If the second operand is positive then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. 如果第二个操作数为正,则向左移位;否则将向右移动。移到系数中的数字为零。The sign and exponent of the first operand are unchanged.第一个操作数的符号和指数不变。

sqrt(context=None)

Return the square root of the argument to full precision.将参数的平方根返回到完全精度。

to_eng_string(context=None)

Convert to a string, using engineering notation if an exponent is needed.如果需要指数,则使用工程符号转换为字符串。

Engineering notation has an exponent which is a multiple of 3. 工程符号的指数是3的倍数。This can leave up to 3 digits to the left of the decimal place and may require the addition of either one or two trailing zeros.这可能会在小数点左侧留下最多3位数字,并且可能需要添加一个或两个尾随零。

For example, this converts Decimal('123E+1') to Decimal('1.23E+3').例如,这将Decimal('123E+1')转换为Decimal('1.23E+3')

to_integral(rounding=None, context=None)

Identical to the to_integral_value() method. to_integral_value()方法相同。The to_integral name has been kept for compatibility with older versions.为了与旧版本兼容,保留了to_integral名称。

to_integral_exact(rounding=None, context=None)

Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. 舍入到最接近的整数,表示Inexact,如果发生舍入,则视情况舍入。The rounding mode is determined by the rounding parameter if given, else by the given context. 舍入模式由rounding参数(如果给定)决定,否则由给定的context决定。If neither parameter is given then the rounding mode of the current context is used.如果两个参数均未给定,则使用当前上下文的舍入模式。

to_integral_value(rounding=None, context=None)

Round to the nearest integer without signaling Inexact or Rounded. 四舍五入到最接近的整数,而不表示InexactRoundedIf given, applies rounding; otherwise, uses the rounding method in either the supplied context or the current context.如果给定,则应用rounding;否则,在提供的上下文或当前context中使用舍入方法。

Logical operands逻辑操作数

The logical_and(), logical_invert(), logical_or(), and logical_xor() methods expect their arguments to be logical operands. logical_and()logical_invert()logical_or()logical_xor()方法期望其参数为逻辑操作数。A logical operand is a Decimal instance whose exponent and sign are both zero, and whose digits are all either 0 or 1.逻辑操作数是一个Decimal实例,其指数和符号均为零,其数字均为01

Context objects上下文对象

Contexts are environments for arithmetic operations. 上下文是算术运算的环境。They govern precision, set rules for rounding, determine which signals are treated as exceptions, and limit the range for exponents.它们控制精度,设置舍入规则,确定哪些信号被视为例外,并限制指数的范围。

Each thread has its own current context which is accessed or changed using the getcontext() and setcontext() functions:每个线程都有自己的当前上下文,可以使用getcontext()setcontext()函数访问或更改该上下文:

decimal.getcontext()

Return the current context for the active thread.返回活动线程的当前上下文。

decimal.setcontext(c)

Set the current context for the active thread to c.将活动线程的当前上下文设置为c

You can also use the with statement and the localcontext() function to temporarily change the active context.您还可以使用with语句和localcontext()函数临时更改活动上下文。

decimal.localcontext(ctx=None)

Return a context manager that will set the current context for the active thread to a copy of ctx on entry to the with-statement and restore the previous context when exiting the with-statement. 返回一个上下文管理器,该管理器将在with语句的条目上将活动线程的当前上下文设置为ctx的副本,并在退出with语句时恢复以前的上下文。If no context is specified, a copy of the current context is used.如果未指定上下文,则使用当前上下文的副本。

For example, the following code sets the current decimal precision to 42 places, performs a calculation, and then automatically restores the previous context:例如,以下代码将当前小数精度设置为42位,执行计算,然后自动恢复以前的上下文:

from decimal import localcontext
with localcontext() as ctx:
ctx.prec = 42 # Perform a high precision calculation
s = calculate_something()
s = +s # Round the final result back to the default precision

New contexts can also be created using the Context constructor described below. 还可以使用下面描述的Context构造函数创建新上下文。In addition, the module provides three pre-made contexts:此外,该模块还提供了三个预先制作的上下文:

classdecimal.BasicContext

This is a standard context defined by the General Decimal Arithmetic Specification. 这是由通用十进制算术规范定义的标准上下文。Precision is set to nine. 精度设置为9。Rounding is set to ROUND_HALF_UP. 取整设置为ROUND_HALF_UPAll flags are cleared. 清除所有标志。All traps are enabled (treated as exceptions) except Inexact, Rounded, and Subnormal.Inexact(不精确)、Rounded(舍入)和Subnormal(低于正常值)外,所有陷阱均已启用(视为异常)。

Because many of the traps are enabled, this context is useful for debugging.由于启用了许多陷阱,因此此上下文对于调试非常有用。

classdecimal.ExtendedContext

This is a standard context defined by the General Decimal Arithmetic Specification. 这是由通用十进制算术规范定义的标准上下文。Precision is set to nine. 精度设置为9。Rounding is set to ROUND_HALF_EVEN. 舍入设置为ROUND_HALF_EVENAll flags are cleared. 清除所有标志。No traps are enabled (so that exceptions are not raised during computations).没有启用陷阱(因此在计算期间不会引发异常)。

Because the traps are disabled, this context is useful for applications that prefer to have result value of NaN or Infinity instead of raising exceptions. 由于陷阱已禁用,因此此上下文对于希望结果值为NaNInfinity而不是引发异常的应用程序非常有用。This allows an application to complete a run in the presence of conditions that would otherwise halt the program.这允许应用程序在出现可能导致程序停止的情况下完成运行。

classdecimal.DefaultContext

This context is used by the Context constructor as a prototype for new contexts. Context构造函数将此上下文用作新上下文的原型。Changing a field (such a precision) has the effect of changing the default for new contexts created by the Context constructor.更改字段(这样的精度)的效果是更改Context构造函数创建的新上下文的默认值。

This context is most useful in multi-threaded environments. 此上下文在多线程环境中最有用。Changing one of the fields before threads are started has the effect of setting system-wide defaults. 在线程启动之前更改其中一个字段会产生设置系统范围默认值的效果。Changing the fields after threads have started is not recommended as it would require thread synchronization to prevent race conditions.不建议在线程启动后更改字段,因为这需要线程同步以防止争用情况。

In single threaded environments, it is preferable to not use this context at all. 在单线程环境中,最好根本不使用此上下文。Instead, simply create contexts explicitly as described below.相反,只需按如下所述显式创建上下文。

The default values are prec=28, rounding=ROUND_HALF_EVEN, and enabled traps for Overflow, InvalidOperation, and DivisionByZero.默认值为prec=28rounding=ROUND_HALF_EVEN,并启用Overflow陷阱、InvalidOperation陷阱和DivisionByZero陷阱。

In addition to the three supplied contexts, new contexts can be created with the Context constructor.除了提供的三个上下文之外,还可以使用Context构造函数创建新的上下文。

classdecimal.Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)

Creates a new context. If a field is not specified or is None, the default values are copied from the DefaultContext. 创建新的上下文。如果字段未指定或None,则从DefaultContext复制默认值。If the flags field is not specified or is None, all flags are cleared.如果未指定flags字段或flags被指定为None,则清除所有标志。

prec is an integer in the range [1, MAX_PREC] that sets the precision for arithmetic operations in the context.prec是[1, MAX_PREC]范围内的整数,用于设置上下文中算术运算的精度。

The rounding option is one of the constants listed in the section Rounding Modes.rounding选项是舍入模式部分中列出的常数之一。

The traps and flags fields list any signals to be set. trapsflags字段列出了要设置的任何信号。Generally, new contexts should only set traps and leave the flags clear.一般来说,新上下文只应设置陷阱并清除标志。

The Emin and Emax fields are integers specifying the outer limits allowable for exponents. EminEmax字段是指定指数允许的外部极限的整数。Emin must be in the range [MIN_EMIN, 0], Emax in the range [0, MAX_EMAX].Emin必须在[MIN_EMIN, 0]范围内,Emax在[0, MAX_EMAX]范围内。

The capitals field is either 0 or 1 (the default). capitals字段为01(默认值)。If set to 1, exponents are printed with a capital E; otherwise, a lowercase e is used: Decimal('6.02e+23').如果设置为1,则指数用大写E打印;否则,使用小写:Decimal('6.02e+23')

The clamp field is either 0 (the default) or 1. clamp字段为0(默认值)或1。If set to 1, the exponent e of a Decimal instance representable in this context is strictly limited to the range Emin - prec + 1 <= e <= Emax - prec + 1. 如果设置为1,则在此上下文中可表示的Decimal实例的指数e严格限制在范围Emin - prec + 1 <= e <= Emax - prec + 1If clamp is 0 then a weaker condition holds: the adjusted exponent of the Decimal instance is at most Emax. 如果clamp0,则较弱的条件成立:Decimal实例的调整指数最多为EmaxWhen clamp is 1, a large normal number will, where possible, have its exponent reduced and a corresponding number of zeros added to its coefficient, in order to fit the exponent constraints; this preserves the value of the number but loses information about significant trailing zeros. clamp(夹逼)为1时,在可能的情况下,较大的正态数将减少其指数,并在其系数中添加相应数量的零,以拟合指数约束;这将保留数字的值,但会丢失有关重要尾随零的信息。For example:例如:

>>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
Decimal('1.23000E+999')

A clamp value of 1 allows compatibility with the fixed-width decimal interchange formats specified in IEEE 754.1的夹逼值允许与IEEE 754中规定的固定宽度十进制交换格式兼容。

The Context class defines several general purpose methods as well as a large number of methods for doing arithmetic directly in a given context. Context类定义了几个通用方法以及大量在给定上下文中直接执行算术的方法。In addition, for each of the Decimal methods described above (with the exception of the adjusted() and as_tuple() methods) there is a corresponding Context method. 此外,对于上述每种Decimal方法(adjusted()as_tuple()方法除外),都有相应的Context方法。For example, for a Context instance C and Decimal instance x, C.exp(x) is equivalent to x.exp(context=C). 例如,对于Context实例CDecimal实例xC.exp(x)等价于x.exp(context=C)Each Context method accepts a Python integer (an instance of int) anywhere that a Decimal instance is accepted.每个Context方法在接受十进制实例的任何位置都接受Python整数(int的实例)。

clear_flags()

Resets all of the flags to 0.将所有标志重置为0

clear_traps()

Resets all of the traps to 0.将所有陷阱重置为0

New in version 3.3.版本3.3中新增。

copy()

Return a duplicate of the context.返回上下文的副本。

copy_decimal(num)

Return a copy of the Decimal instance num.返回Decimal实例num的副本。

create_decimal(num)

Creates a new Decimal instance from num but using self as context. num创建一个新的Decimal实例,但使用self作为上下文。Unlike the Decimal constructor, the context precision, rounding method, flags, and traps are applied to the conversion.Decimal构造函数不同,上下文精度、舍入方法、标志和陷阱应用于转换。

This is useful because constants are often given to a greater precision than is needed by the application. 这很有用,因为常数的精度通常高于应用程序所需的精度。Another benefit is that rounding immediately eliminates unintended effects from digits beyond the current precision. 另一个好处是舍入可以立即消除超出当前精度的数字的意外影响。In the following example, using unrounded inputs means that adding zero to a sum can change the result:在以下示例中,使用未舍入的输入意味着将零添加到和可以更改结果:

>>> getcontext().prec = 3
>>> Decimal('3.4445') + Decimal('1.0023')
Decimal('4.45')
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44')

This method implements the to-number operation of the IBM specification. 该方法实现了IBM规范的to number操作。If the argument is a string, no leading or trailing whitespace or underscores are permitted.如果参数是字符串,则不允许前导或尾随空格或下划线。

create_decimal_from_float(f)

Creates a new Decimal instance from a float f but rounding using self as the context. 从浮点f创建新的十进制实例,但使用self作为上下文舍入。Unlike the Decimal.from_float() class method, the context precision, rounding method, flags, and traps are applied to the conversion.Decimal.from_float()类方法不同,上下文精度、舍入方法、标志和陷阱应用于转换。

>>> context = Context(prec=5, rounding=ROUND_DOWN)
>>> context.create_decimal_from_float(math.pi)
Decimal('3.1415')
>>> context = Context(prec=5, traps=[Inexact])
>>> context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
...
decimal.Inexact: None

New in version 3.1.版本3.1中新增。

Etiny()

Returns a value equal to Emin - prec + 1 which is the minimum exponent value for subnormal results. 返回等于Emin - prec + 1的值,该值是次正常结果的最小指数值。When underflow occurs, the exponent is set to Etiny.发生下溢时,指数设置为Etiny

Etop()

Returns a value equal to Emax - prec + 1.返回等于Emax - prec + 1的值。

The usual approach to working with decimals is to create Decimal instances and then apply arithmetic operations which take place within the current context for the active thread. 处理十进制数的常用方法是创建Decimal实例,然后对活动线程应用在当前上下文中发生的算术运算。An alternative approach is to use context methods for calculating within a specific context. 另一种方法是使用上下文方法在特定上下文中进行计算。The methods are similar to those for the Decimal class and are only briefly recounted here.这些方法与Decimal类的方法类似,此处仅简要叙述。

abs(x)

Returns the absolute value of x.返回x的绝对值。

add(x, y)

Return the sum of x and y.返回xy的总和。

canonical(x)

Returns the same Decimal object x.返回相同的十进制对象x

compare(x, y)

Compares x and y numerically.在数值上比较xy

compare_signal(x, y)

Compares the values of the two operands numerically.以数字方式比较两个操作数的值。

compare_total(x, y)

Compares two operands using their abstract representation.使用抽象表示法比较两个操作数。

compare_total_mag(x, y)

Compares two operands using their abstract representation, ignoring sign.使用抽象表示法比较两个操作数,忽略符号。

copy_abs(x)

Returns a copy of x with the sign set to 0.返回符号设置为0的x的副本。

copy_negate(x)

Returns a copy of x with the sign inverted.返回带反转符号的x的副本。

copy_sign(x, y)

Copies the sign from y to x.将符号从y复制到x

divide(x, y)

Return x divided by y.返回x除以y

divide_int(x, y)

Return x divided by y, truncated to an integer.返回x除以y,截断为整数。

divmod(x, y)

Divides two numbers and returns the integer part of the result.将两个数字相除并返回结果的整数部分。

exp(x)

Returns e ** x.返回e ** x

fma(x, y, z)

Returns x multiplied by y, plus z.返回x乘以yz

is_canonical(x)

Returns True if x is canonical; otherwise returns False.如果x是正则的,则返回True;否则返回False

is_finite(x)

Returns True if x is finite; otherwise returns False.如果x是有限的,则返回True;否则返回False

is_infinite(x)

Returns True if x is infinite; otherwise returns False.如果x为无穷大,则返回True;否则返回False

is_nan(x)

Returns True if x is a qNaN or sNaN; otherwise returns False.如果x是qNaN或sNaN,则返回True;否则返回False

is_normal(x)

Returns True if x is a normal number; otherwise returns False.如果x是正常数,则返回True;否则返回False

is_qnan(x)

Returns True if x is a quiet NaN; otherwise returns False.如果x是安静的NaN,则返回True;否则返回False

is_signed(x)

Returns True if x is negative; otherwise returns False.如果x为负,则返回True;否则返回False

is_snan(x)

Returns True if x is a signaling NaN; otherwise returns False.如果x是信号NaN,则返回True;否则返回False

is_subnormal(x)

Returns True if x is subnormal; otherwise returns False.如果x低于正常值,则返回True;否则返回False

is_zero(x)

Returns True if x is a zero; otherwise returns False.如果x为零,则返回True;否则返回False

ln(x)

Returns the natural (base e) logarithm of x.返回x的自然对数(以e为底)。

log10(x)

Returns the base 10 logarithm of x.返回x的以10为底的对数。

logb(x)

Returns the exponent of the magnitude of the operand’s MSD.返回操作数MSD的幅值指数。

logical_and(x, y)

Applies the logical operation and between each operand’s digits.在每个操作数的位数之间应用逻辑运算and

logical_invert(x)

Invert all the digits in x.反转x中的所有数字。

logical_or(x, y)

Applies the logical operation or between each operand’s digits.在每个操作数的位数之间应用逻辑运算or

logical_xor(x, y)

Applies the logical operation xor between each operand’s digits.在每个操作数的位数之间应用逻辑运算xor

max(x, y)

Compares two values numerically and returns the maximum.比较两个数值并返回最大值。

max_mag(x, y)

Compares the values numerically with their sign ignored.比较忽略符号的数值。

min(x, y)

Compares two values numerically and returns the minimum.比较两个数值并返回最小值。

min_mag(x, y)

Compares the values numerically with their sign ignored.比较忽略符号的数值。

minus(x)

Minus corresponds to the unary prefix minus operator in Python.减号对应于Python中的一元前缀减号运算符。

multiply(x, y)

Return the product of x and y.返回xy的乘积。

next_minus(x)

Returns the largest representable number smaller than x.返回小于x的最大可表示数。

next_plus(x)

Returns the smallest representable number larger than x.返回大于x的最小可表示数。

next_toward(x, y)

Returns the number closest to x, in direction towards y.返回沿y方向最接近x的数字。

normalize(x)

Reduces x to its simplest form.x简化为最简单的形式。

number_class(x)

Returns an indication of the class of x.返回x类的指示。

plus(x)

Plus corresponds to the unary prefix plus operator in Python. 加号对应于Python中的一元前缀加号运算符。This operation applies the context precision and rounding, so it is not an identity operation.此操作应用上下文精度和舍入,因此它不是标识操作。

power(x, y, modulo=None)

Return x to the power of y, reduced modulo modulo if given.x返回到y的幂,如果给定,则为约化模modulo

With two arguments, compute x**y. 使用两个参数,计算x**yIf x is negative then y must be integral. 如果x是负的,那么y必须是整数。The result will be inexact unless y is integral and the result is finite and can be expressed exactly in ‘precision’ digits. 除非y是整数,并且结果是有限的,并且可以精确地用“精度”数字表示,否则结果将是不精确的。The rounding mode of the context is used. 使用上下文的舍入模式。Results are always correctly-rounded in the Python version.在Python版本中,结果总是正确地四舍五入。

Decimal(0) ** Decimal(0) results in InvalidOperation, and if InvalidOperation is not trapped, then results in Decimal('NaN').Decimal(0) ** Decimal(0)导致InvalidOperation,如果未捕获InvalidOperation,则导致Decimal('NaN')

Changed in version 3.3:版本3.3中更改: The C module computes power() in terms of the correctly-rounded exp() and ln() functions. C模块根据正确舍入的exp()ln()函数计算power()The result is well-defined but only “almost always correctly-rounded”.结果定义明确,但“几乎总是正确四舍五入”。

With three arguments, compute (x**y) % modulo. 使用三个参数,计算(x**y) % moduloFor the three argument form, the following restrictions on the arguments hold:对于三参数形式,对参数有以下限制:

  • all three arguments must be integral这三个参数都必须是整数

  • y must be nonnegative必须为非负

  • at least one of x or y must be nonzeroxy中至少有一个必须为非零

  • modulo must be nonzero and have at most ‘precision’ digits必须为非零且最多包含“精度”数字

The value resulting from Context.power(x, y, modulo) is equal to the value that would be obtained by computing (x**y) % modulo with unbounded precision, but is computed more efficiently. Context.power(x, y, modulo)得到的值等于以无限精度计算(x**y) % modulo得到的值,但计算效率更高。The exponent of the result is zero, regardless of the exponents of x, y and modulo. 结果的指数为零,与xymodulo的指数无关。The result is always exact.结果总是准确的。

quantize(x, y)

Returns a value equal to x (rounded), having the exponent of y.返回一个等于x(四舍五入)的值,其指数为y

radix()

Just returns 10, as this is Decimal, 只返回10,因为这是十进制,:)

remainder(x, y)

Returns the remainder from integer division.返回整数除法的余数。

The sign of the result, if non-zero, is the same as that of the original dividend.如果结果的符号不为零,则与原始股息的符号相同。

remainder_near(x, y)

Returns x - y * n, where n is the integer nearest the exact value of x / y (if the result is 0 then its sign will be the sign of x).返回x-y*n,其中n是最接近x/y的精确值的整数(如果结果为0,则其符号将为x的符号)。

rotate(x, y)

Returns a rotated copy of x, y times.返回xy次的旋转副本。

same_quantum(x, y)

Returns True if the two operands have the same exponent.如果两个操作数的指数相同,则返回True

scaleb(x, y)

Returns the first operand after adding the second value its exp.将第二个值与exp相加后返回第一个操作数。

shift(x, y)

Returns a shifted copy of x, y times.返回xy时间的移位副本。

sqrt(x)

Square root of a non-negative number to context precision.非负数的平方根到上下文精度。

subtract(x, y)

Return the difference between x and y.返回xy之间的差值。

to_eng_string(x)

Convert to a string, using engineering notation if an exponent is needed.如果需要指数,则使用工程符号转换为字符串。

Engineering notation has an exponent which is a multiple of 3. 工程符号的指数是3的倍数。This can leave up to 3 digits to the left of the decimal place and may require the addition of either one or two trailing zeros.这可能会在小数点左侧留下最多3位数字,并且可能需要添加一个或两个尾随零。

to_integral_exact(x)

Rounds to an integer.舍入为整数。

to_sci_string(x)

Converts a number to a string using scientific notation.使用科学记数法将数字转换为字符串。

Constants常数

The constants in this section are only relevant for the C module. 本节中的常数仅与C模块相关。They are also included in the pure Python version for compatibility.为了兼容性,纯Python版本中也包含了它们。

32-bit

64-bit

decimal.MAX_PREC

425000000

999999999999999999

decimal.MAX_EMAX

425000000

999999999999999999

decimal.MIN_EMIN

-425000000

-999999999999999999

decimal.MIN_ETINY

-849999999

-1999999999999999997

decimal.HAVE_THREADS

The value is True. 该值为TrueDeprecated, because Python now always has threads.已弃用,因为Python现在总是有线程。

Deprecated since version 3.9.自版本3.9以来已弃用。

decimal.HAVE_CONTEXTVAR

The default value is True. 默认值为TrueIf Python is configured using the --without-decimal-contextvar option, the C version uses a thread-local rather than a coroutine-local context and the value is False. 如果Python为configured using the --without-decimal-contextvar option,则C版本使用线程局部上下文而不是协程局部上下文,并且该值为FalseThis is slightly faster in some nested context scenarios.在某些嵌套上下文场景中,这稍微快一点。

New in version 3.9.版本3.9中新增。backported to 3.7 and 3.8.后端口为3.7和3.8。

Rounding modes舍入模式

decimal.ROUND_CEILING

Round towards Infinity.Infinity方向旋转。

decimal.ROUND_DOWN

Round towards zero.四舍五入到零。

decimal.ROUND_FLOOR

Round towards -Infinity.-Infinity方向旋转。

decimal.ROUND_HALF_DOWN

Round to nearest with ties going towards zero.四舍五入到最近,平局接近零。

decimal.ROUND_HALF_EVEN

Round to nearest with ties going to nearest even integer.四舍五入到最近值,关系式到最近的偶数整数。

decimal.ROUND_HALF_UP

Round to nearest with ties going away from zero.四舍五入到最近,平局从零开始。

decimal.ROUND_UP

Round away from zero.从零开始取整。

decimal.ROUND_05UP

Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero.如果向零取整后的最后一位数字为0或5,则从零取整;否则,向零舍入。

Signals信号

Signals represent conditions that arise during computation. 信号表示计算过程中出现的条件。Each corresponds to one context flag and one context trap enabler.每个对应于一个上下文标志和一个上下文陷阱启用码。

The context flag is set whenever the condition is encountered. 只要遇到条件,就会设置上下文标志。After the computation, flags may be checked for informational purposes (for instance, to determine whether a computation was exact). 计算后,可以出于信息目的检查标志(例如,确定计算是否准确)。After checking the flags, be sure to clear all flags before starting the next computation.检查标志后,确保在开始下一次计算之前清除所有标志。

If the context’s trap enabler is set for the signal, then the condition causes a Python exception to be raised. 如果为信号设置了上下文的陷阱启用码,则该条件会引发Python异常。For example, if the DivisionByZero trap is set, then a DivisionByZero exception is raised upon encountering the condition.例如,如果设置了DivisionByZero陷阱,则在遇到该条件时会引发DivisionByZero异常。

classdecimal.Clamped

Altered an exponent to fit representation constraints.修改指数以适应表示约束。

Typically, clamping occurs when an exponent falls outside the context’s Emin and Emax limits. 通常,当指数超出上下文的Emin和Emax限制时,会发生钳制。If possible, the exponent is reduced to fit by adding zeros to the coefficient.如果可能,通过在系数中添加零来减小指数以进行拟合。

classdecimal.DecimalException

Base class for other signals and a subclass of ArithmeticError.其他信号的基类和ArithmeticError的子类。

classdecimal.DivisionByZero

Signals the division of a non-infinite number by zero.表示非无限数除以零。

Can occur with division, modulo division, or when raising a number to a negative power. 可以使用除法、模除法或将数字提高到负幂时发生。If this signal is not trapped, returns Infinity or -Infinity with the sign determined by the inputs to the calculation.如果该信号未被捕获,则返回Infinity-Infinity,其符号由计算的输入确定。

classdecimal.Inexact

Indicates that rounding occurred and the result is not exact.表示发生舍入,结果不准确。

Signals when non-zero digits were discarded during rounding. 舍入期间丢弃非零数字时的信号。The rounded result is returned. 返回舍入结果。The signal flag or trap is used to detect when results are inexact.信号标志或陷阱用于检测结果不精确的情况。

classdecimal.InvalidOperation

An invalid operation was performed.执行了无效的操作。

Indicates that an operation was requested that does not make sense. 指示请求的操作没有意义。If not trapped, returns NaN. 如果没有被困住,返回NaNPossible causes include:可能的原因包括:

Infinity - Infinity
0 * Infinity
Infinity / Infinity
x % 0
Infinity % x
sqrt(-x) and x > 0
0 ** 0
x ** (non-integer)
x ** Infinity
classdecimal.Overflow

Numerical overflow.数值溢出。

Indicates the exponent is larger than Emax after rounding has occurred. 表示舍入后指数大于EmaxIf not trapped, the result depends on the rounding mode, either pulling inward to the largest representable finite number or rounding outward to Infinity. 如果没有被捕获,结果取决于取整模式,要么向内拉到最大的可表示有限数,要么向外取整到InfinityIn either case, Inexact and Rounded are also signaled.在这两种情况下,InexactRounded也会发出信号。

classdecimal.Rounded

Rounding occurred though possibly no information was lost.舍入发生,但可能没有丢失任何信息。

Signaled whenever rounding discards digits; even if those digits are zero (such as rounding 5.00 to 5.0). 四舍五入丢弃数字时发出信号;即使这些数字为零(例如四舍五入5.005.0)。If not trapped, returns the result unchanged. 如果未捕获,则返回不变的结果。This signal is used to detect loss of significant digits.该信号用于检测有效数字的丢失。

classdecimal.Subnormal

Exponent was lower than Emin prior to rounding.在取整之前,指数低于Emin

Occurs when an operation result is subnormal (the exponent is too small). 当运算结果低于正常值(指数太小)时发生。If not trapped, returns the result unchanged.如果未捕获,则返回不变的结果。

classdecimal.Underflow

Numerical underflow with result rounded to zero.数值下溢,结果四舍五入为零。

Occurs when a subnormal result is pushed to zero by rounding. 当通过舍入将低于正常值的结果推到零时发生。Inexact and Subnormal are also signaled.也会发出InexactSubnormal的信号。

classdecimal.FloatOperation

Enable stricter semantics for mixing floats and Decimals.为混合浮点和小数启用更严格的语义。

If the signal is not trapped (default), mixing floats and Decimals is permitted in the Decimal constructor, create_decimal() and all comparison operators. 如果未捕获信号(默认),则允许在Decimal构造函数、create_decimal()和所有比较运算符中混合浮点和小数。Both conversion and comparisons are exact. 转换和比较都是精确的。Any occurrence of a mixed operation is silently recorded by setting FloatOperation in the context flags. 通过在上下文标志中设置FloatOperation,将静默记录任何混合操作的发生。Explicit conversions with from_float() or create_decimal_from_float() do not set the flag.使用from_float()create_decimal_from_float()的显式转换不设置标志。

Otherwise (the signal is trapped), only equality comparisons and explicit conversions are silent. 否则(信号被捕获),只有相等比较和显式转换是静默的。All other mixed operations raise FloatOperation.所有其他混合操作都会引发FloatOperation

The following table summarizes the hierarchy of signals:下表总结了信号的层次结构:

exceptions.ArithmeticError(exceptions.Exception)
DecimalException
Clamped
DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
Inexact
Overflow(Inexact, Rounded)
Underflow(Inexact, Rounded, Subnormal)
InvalidOperation
Rounded
Subnormal
FloatOperation(DecimalException, exceptions.TypeError)

Floating Point Notes浮点注释

Mitigating round-off error with increased precision降低舍入误差,提高精度

The use of decimal floating point eliminates decimal representation error (making it possible to represent 0.1 exactly); however, some operations can still incur round-off error when non-zero digits exceed the fixed precision.十进制浮点的使用消除了十进制表示错误(使得能够精确表示0.1);然而,当非零数字超过固定精度时,某些操作仍然会产生舍入误差。

The effects of round-off error can be amplified by the addition or subtraction of nearly offsetting quantities resulting in loss of significance. 舍入误差的影响可以通过增加或减少几乎抵消的量来放大,从而导致显著性损失。Knuth provides two instructive examples where rounded floating point arithmetic with insufficient precision causes the breakdown of the associative and distributive properties of addition:Knuth提供了两个具有指导意义的示例,其中精度不足的四舍五入浮点算法导致加法的关联和分布属性崩溃:

# Examples from Seminumerical Algorithms, Section 4.2.2.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 8
>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.5111111')
>>> u + (v + w)
Decimal('10')

>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.01')
>>> u * (v+w)
Decimal('0.0060000')

The decimal module makes it possible to restore the identities by expanding the precision sufficiently to avoid loss of significance:decimal模块可以通过充分扩展精度来恢复恒等式,以避免显著性损失:

>>> getcontext().prec = 20
>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.51111111')
>>> u + (v + w)
Decimal('9.51111111')
>>>
>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.0060000')
>>> u * (v+w)
Decimal('0.0060000')

Special values特殊值

The number system for the decimal module provides special values including NaN, sNaN, -Infinity, Infinity, and two zeros, +0 and -0.decimal模块的数字系统提供特殊值,包括NaNsNaN-InfinityInfinity和两个零+0-0

Infinities can be constructed directly with: Decimal('Infinity'). 无穷大可以直接用Decimal('Infinity')构造。Also, they can arise from dividing by zero when the DivisionByZero signal is not trapped. 此外,当DivisionByZero信号未被捕获时,它们可能由零除引起。Likewise, when the Overflow signal is not trapped, infinity can result from rounding beyond the limits of the largest representable number.同样,当Overflow信号未被捕获时,舍入超过最大可表示数的限制可能导致无穷大。

The infinities are signed (affine) and can be used in arithmetic operations where they get treated as very large, indeterminate numbers. 无穷大是有符号(仿射)的,可以用于算术运算,其中它们被视为非常大的不确定数。For instance, adding a constant to infinity gives another infinite result.例如,将一个常数添加到无穷大中会得到另一个无穷大的结果。

Some operations are indeterminate and return NaN, or if the InvalidOperation signal is trapped, raise an exception. 有些操作是不确定的,返回NaN,或者如果捕获了InvalidOperation信号,则引发异常。For example, 0/0 returns NaN which means “not a number”. 例如,0/0返回NaN,表示“不是数字”。This variety of NaN is quiet and, once created, will flow through other computations always resulting in another NaN. 这种类型的NaN是安静的,一旦创建,将流经其他计算,始终会产生另一个NaNThis behavior can be useful for a series of computations that occasionally have missing inputs — it allows the calculation to proceed while flagging specific results as invalid.这种行为对于偶尔缺少输入的一系列计算非常有用-它允许计算继续进行,同时将特定结果标记为无效。

A variant is sNaN which signals rather than remaining quiet after every operation. sNaN是一种变体,它发出信号,而不是在每次操作后保持安静。This is a useful return value when an invalid result needs to interrupt a calculation for special handling.当无效结果需要中断计算以进行特殊处理时,这是一个有用的返回值。

The behavior of Python’s comparison operators can be a little surprising where a NaN is involved. Python的比较运算符的行为在涉及NaN的地方可能有点令人惊讶。A test for equality where one of the operands is a quiet or signaling NaN always returns False (even when doing Decimal('NaN')==Decimal('NaN')), while a test for inequality always returns True. 当其中一个操作数为静默或信号NaN时,相等测试始终返回False(即使在执行Decimal('NaN')==Decimal('NaN')),而不相等测试始终返回TrueAn attempt to compare two Decimals using any of the <, <=, > or >= operators will raise the InvalidOperation signal if either operand is a NaN, and return False if this signal is not trapped. 如果使用任何<<=>>=运算符比较两个小数,则如果其中一个操作数是NaN,则会引发InvalidOperation信号,如果未捕获该信号,则返回FalseNote that the General Decimal Arithmetic specification does not specify the behavior of direct comparisons; these rules for comparisons involving a NaN were taken from the IEEE 854 standard (see Table 3 in section 5.7). 注意,一般的十进制算术规范没有规定直接比较的行为;这些涉及NaN的比较规则取自IEEE 854标准(见第5.7节表3)。To ensure strict standards-compliance, use the compare() and compare-signal() methods instead.为了确保严格遵守标准,请改用compare()compare-signal()方法。

The signed zeros can result from calculations that underflow. 符号零可以由下溢的计算得出。They keep the sign that would have resulted if the calculation had been carried out to greater precision. 他们保留了如果计算更精确的话会产生的符号。Since their magnitude is zero, both positive and negative zeros are treated as equal and their sign is informational.由于其幅值为零,正零和负零均被视为相等,其符号具有信息性。

In addition to the two signed zeros which are distinct yet equal, there are various representations of zero with differing precisions yet equivalent in value. 除了两个不同但相等的有符号零外,还有各种精度不同但值相等的零表示。This takes a bit of getting used to. 这需要一点习惯。For an eye accustomed to normalized floating point representations, it is not immediately obvious that the following calculation returns a value equal to zero:对于习惯于标准化浮点表示的眼睛,以下计算返回等于零的值并不立即明显:

>>> 1 / Decimal('Infinity')
Decimal('0E-1000026')

Working with threads使用线程

The getcontext() function accesses a different Context object for each thread. getcontext()函数的作用是:为每个线程访问不同的Context对象。Having separate thread contexts means that threads may make changes (such as getcontext().prec=10) without interfering with other threads.具有单独的线程上下文意味着线程可以在不干扰其他线程的情况下进行更改(例如getcontext().prec=10)。

Likewise, the setcontext() function automatically assigns its target to the current thread.同样,setcontext()函数会自动将其目标分配给当前线程。

If setcontext() has not been called before getcontext(), then getcontext() will automatically create a new context for use in the current thread.如果在getcontext()之前未调用setcontext(),则getcontext()将自动创建一个新的上下文以在当前线程中使用。

The new context is copied from a prototype context called DefaultContext. 新上下文是从名为DefaultContext的原型上下文复制而来的。To control the defaults so that each thread will use the same values throughout the application, directly modify the DefaultContext object. 要控制默认值,以便每个线程在整个应用程序中使用相同的值,请直接修改DefaultContext对象。This should be done before any threads are started so that there won’t be a race condition between threads calling getcontext(). 这应该在启动任何线程之前完成,这样调用getcontext()的线程之间就不会出现争用条件。For example:例如:

# Set applicationwide defaults for all threads about to be launched
DefaultContext.prec = 12
DefaultContext.rounding = ROUND_DOWN
DefaultContext.traps = ExtendedContext.traps.copy()
DefaultContext.traps[InvalidOperation] = 1
setcontext(DefaultContext)
# Afterwards, the threads can be started
t1.start()
t2.start()
t3.start()
. . .

Recipes食谱

Here are a few recipes that serve as utility functions and that demonstrate ways to work with the Decimal class:以下是一些用作实用函数的方法,演示了使用Decimal类的方法:

def moneyfmt(value, places=2, curr='', sep=',', dp='.',
pos='', neg='-', trailneg=''):
"""Convert Decimal to a money formatted string.
places: required number of places after the decimal point
curr: optional currency symbol before the sign (may be blank)
sep: optional grouping separator (comma, period, space, or blank)
dp: decimal point indicator (comma or period)
only specify as blank when places is zero
pos: optional sign for positive numbers: '+', space or blank
neg: optional sign for negative numbers: '-', '(', space or blank
trailneg:optional trailing minus indicator: '-', ')', space or blank

>>> d = Decimal('-1234567.8901')
>>> moneyfmt(d, curr='$')
'-$1,234,567.89'
>>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
'1.234.568-'
>>> moneyfmt(d, curr='$', neg='(', trailneg=')')
'($1,234,567.89)'
>>> moneyfmt(Decimal(123456789), sep=' ')
'123 456 789.00'
>>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
'<0.02>'

"""
q = Decimal(10) ** -places # 2 places --> '0.01'
sign, digits, exp = value.quantize(q).as_tuple()
result = []
digits = list(map(str, digits))
build, next = result.append, digits.pop
if sign:
build(trailneg)
for i in range(places):
build(next() if digits else '0')
if places:
build(dp)
if not digits:
build('0')
i = 0
while digits:
build(next())
i += 1
if i == 3 and digits:
i = 0
build(sep)
build(curr)
build(neg if sign else pos)
return ''.join(reversed(result))

def pi():
"""Compute Pi to the current precision.

>>> print(pi())
3.141592653589793238462643383

"""
getcontext().prec += 2 # extra digits for intermediate steps
three = Decimal(3) # substitute "three=3.0" for regular floats
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
getcontext().prec -= 2
return +s # unary plus applies the new precision

def exp(x):
"""Return e raised to the power of x. Result type matches input type.

>>> print(exp(Decimal(1)))
2.718281828459045235360287471
>>> print(exp(Decimal(2)))
7.389056098930650227230427461
>>> print(exp(2.0))
7.38905609893
>>> print(exp(2+0j))
(7.38905609893+0j)

"""
getcontext().prec += 2
i, lasts, s, fact, num = 0, 0, 1, 1, 1
while s != lasts:
lasts = s
i += 1
fact *= i
num *= x
s += num / fact
getcontext().prec -= 2
return +s

def cos(x):
"""Return the cosine of x as measured in radians.

The Taylor series approximation works best for a small value of x.
For larger values, first compute x = x % (2 * pi).

>>> print(cos(Decimal('0.5')))
0.8775825618903727161162815826
>>> print(cos(0.5))
0.87758256189
>>> print(cos(0.5+0j))
(0.87758256189+0j)

"""
getcontext().prec += 2
i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
while s != lasts:
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
getcontext().prec -= 2
return +s

def sin(x):
"""Return the sine of x as measured in radians.

The Taylor series approximation works best for a small value of x.
For larger values, first compute x = x % (2 * pi).

>>> print(sin(Decimal('0.5')))
0.4794255386042030002732879352
>>> print(sin(0.5))
0.479425538604
>>> print(sin(0.5+0j))
(0.479425538604+0j)

"""
getcontext().prec += 2
i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
while s != lasts:
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
getcontext().prec -= 2
return +s

Decimal FAQ十进制常见问题解答

Q. It is cumbersome to type decimal.Decimal('1234.5'). 键入decimal.Decimal('1234.5')很麻烦。Is there a way to minimize typing when using the interactive interpreter?在使用交互式口译员时,有没有办法尽量减少键入?

A. Some users abbreviate the constructor to just a single letter:一些用户将构造函数缩写为一个字母:

>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Decimal('4.68')

Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. 在小数点后两位的定点应用程序中,一些输入有许多位,需要四舍五入。Others are not supposed to have excess digits and need to be validated. 其他人不应该有多余的数字,需要验证。What methods should be used?应该使用什么方法?

A. The quantize() method rounds to a fixed number of decimal places. quantize()方法舍入到固定的小数位数。If the Inexact trap is set, it is also useful for validation:如果设置了Inexact陷阱,它也有助于验证:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None

Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?一旦有了有效的两位输入,如何在整个应用程序中保持不变?

A. Some operations like addition, subtraction, and multiplication by an integer will automatically preserve fixed point. 某些运算,如整数的加法、减法和乘法,将自动保持不动点。Others operations, like division and non-integer multiplication, will change the number of decimal places and need to be followed-up with a quantize() step:其他操作,如除法和非整数乘法,将改变小数位数,需要执行quantize()步骤:

>>> a = Decimal('102.72')           # Initial fixed-point values
>>> b = Decimal('3.17')
>>> a + b # Addition preserves fixed-point
Decimal('105.89')
>>> a - b
Decimal('99.55')
>>> a * 42 # So does integer multiplication
Decimal('4314.24')
>>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
Decimal('325.62')
>>> (b / a).quantize(TWOPLACES) # And quantize division
Decimal('0.03')

In developing fixed-point applications, it is convenient to define functions to handle the quantize() step:在开发定点应用程序时,可以方便地定义函数来处理quantize()步骤:

>>> def mul(x, y, fp=TWOPLACES):
... return (x * y).quantize(fp)
>>> def div(x, y, fp=TWOPLACES):
... return (x / y).quantize(fp)
>>> mul(a, b)                       # Automatically preserve fixed-point
Decimal('325.62')
>>> div(b, a)
Decimal('0.03')

Q. There are many ways to express the same value. 有许多方法可以表达相同的价值。The numbers 200, 200.000, 2E2, and 02E+4 all have the same value at various precisions. 数字200200.0002E202E+4在不同精度下都具有相同的值。Is there a way to transform them to a single recognizable canonical value?有没有办法将它们转换为单个可识别的规范值?

A. The normalize() method maps all equivalent values to a single representative:normalize()方法将所有等效值映射到单个代表:

>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]

Q. Some decimal values always print with exponential notation. 一些十进制值总是以指数表示法打印。Is there a way to get a non-exponential representation?有没有办法得到非指数表示?

A. For some values, exponential notation is the only way to express the number of significant places in the coefficient. 对于某些值,指数表示法是表示系数中有效位数的唯一方法。For example, expressing 5.0E+3 as 5000 keeps the value constant but cannot show the original’s two-place significance.例如,将5.0E+3表示为5000可以保持值不变,但无法显示原始值的两位意义。

If an application does not care about tracking significance, it is easy to remove the exponent and trailing zeroes, losing significance, but keeping the value unchanged:如果应用程序不关心跟踪显著性,则很容易删除指数和尾随零,从而失去显著性,但保持值不变:

>>> def remove_exponent(d):
... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')

Q. Is there a way to convert a regular float to a Decimal?有没有办法将常规浮点转换为Decimal

A. Yes, any binary floating point number can be exactly expressed as a Decimal though an exact conversion may take more precision than intuition would suggest:是的,任何二进制浮点数都可以精确表示为十进制,尽管精确转换可能需要比直觉所建议的更高的精度:

>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')

Q. Within a complex calculation, how can I make sure that I haven’t gotten a spurious result because of insufficient precision or rounding anomalies.在一个复杂的计算中,我如何确保没有因为精度不足或舍入异常而得到虚假的结果。

A. The decimal module makes it easy to test results. 十进制模块使测试结果变得容易。A best practice is to re-run calculations using greater precision and with various rounding modes. 最佳做法是使用更高精度和各种舍入模式重新运行计算。Widely differing results indicate insufficient precision, rounding mode issues, ill-conditioned inputs, or a numerically unstable algorithm.差异很大的结果表明精度不足、舍入模式问题、病态输入或数值不稳定的算法。

Q. I noticed that context precision is applied to the results of operations but not to the inputs. 我注意到上下文精度适用于操作结果,但不适用于输入。Is there anything to watch out for when mixing values of different precisions?当混合不同精度的值时,有什么需要注意的吗?

A. Yes. The principle is that all values are considered to be exact and so is the arithmetic on those values. 原则是,所有值都被认为是精确的,对这些值的算术也是精确的。Only the results are rounded. 只有结果是四舍五入的。The advantage for inputs is that “what you type is what you get”. 输入的优点是“你输入的就是你得到的”。A disadvantage is that the results can look odd if you forget that the inputs haven’t been rounded:一个缺点是,如果您忘记输入尚未四舍五入,结果可能看起来很奇怪:

>>> getcontext().prec = 3
>>> Decimal('3.104') + Decimal('2.104')
Decimal('5.21')
>>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Decimal('5.20')

The solution is either to increase precision or to force rounding of inputs using the unary plus operation:解决方案是提高精度或使用一元加运算强制输入舍入:

>>> getcontext().prec = 3
>>> +Decimal('1.23456789') # unary plus triggers rounding
Decimal('1.23')

Alternatively, inputs can be rounded upon creation using the Context.create_decimal() method:或者,输入可以在创建时使用Context.create_decimal()方法四舍五入:

>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')

Q. Is the CPython implementation fast for large numbers?CPython实现对于大数字来说是否快速?

A. Yes. 对。In the CPython and PyPy3 implementations, the C/CFFI versions of the decimal module integrate the high speed libmpdec library for arbitrary precision correctly-rounded decimal floating point arithmetic 1. 在CPython和PyPy3实现中,十进制模块的C/CFFI版本集成了高速libmpdec库,以实现任意精度的正确舍入十进制浮点算术1libmpdec uses Karatsuba multiplication for medium-sized numbers and the Number Theoretic Transform for very large numbers.libmpdec对中等大小的数字使用Karatsuba乘法,对非常大的数字使用数论变换

The context must be adapted for exact arbitrary precision arithmetic. 上下文必须适用于精确的任意精度算法。Emin and Emax should always be set to the maximum values, clamp should always be 0 (the default). EminEmax应始终设置为最大值,clamp应始终为0(默认值)。Setting prec requires some care.设置prec需要一些注意。

The easiest approach for trying out bignum arithmetic is to use the maximum value for prec as well 2:试用bignum算法的最简单方法是使用prec的最大值2

>>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
>>> x = Decimal(2) ** 256
>>> x / 128
Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')

For inexact results, MAX_PREC is far too large on 64-bit platforms and the available memory will be insufficient:对于不精确的结果,MAX_PREC在64位平台上太大,可用内存不足:

>>> Decimal(1) / 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError

On systems with overallocation (e.g. Linux), a more sophisticated approach is to adjust prec to the amount of available RAM. 在具有过度分配的系统(例如Linux)上,更复杂的方法是将prec调整到可用RAM的数量。Suppose that you have 8GB of RAM and expect 10 simultaneous operands using a maximum of 500MB each:假设您有8GB的RAM,并且期望同时有10个操作数,每个操作数的最大值为500MB:

>>> import sys
>>>
>>> # Maximum number of digits for a single operand using 500MB in 8-byte words
>>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
>>> maxdigits = 19 * ((500 * 1024**2) // 8)
>>>
>>> # Check that this works:
>>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
>>> c.traps[Inexact] = True
>>> setcontext(c)
>>>
>>> # Fill the available precision with nines:
>>> x = Decimal(0).logical_invert() * 9
>>> sys.getsizeof(x)
524288112
>>> x + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.Inexact: [<class 'decimal.Inexact'>]

In general (and especially on systems without overallocation), it is recommended to estimate even tighter bounds and set the Inexact trap if all calculations are expected to be exact.一般来说(尤其是在没有过度分配的系统上),如果所有计算都是精确的,建议估计更严格的界限并设置Inexact陷阱。

1

New in version 3.3.版本3.3中新增。

2

Changed in version 3.9:版本3.9中更改: This approach now works for all exact results except for non-integer powers.这种方法现在适用于除非整数幂外的所有精确结果。