“Python/docs/3.9/library/decimal”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/decimal
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:十进制 — 十进制定点和浮点运算 — Python 文档}}
 
<div id="module-decimal" class="section">
 
<div id="module-decimal" class="section">
  
 
<span id="decimal-decimal-fixed-point-and-floating-point-arithmetic"></span>
 
<span id="decimal-decimal-fixed-point-and-floating-point-arithmetic"></span>
= [[#module-decimal|<code>decimal</code>]] --- Decimal fixed point and floating point arithmetic =
+
= decimal — 十进制定点和浮点运算 =
  
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/decimal.py Lib/decimal.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/decimal.py`</span>]]
  
The [[#module-decimal|<code>decimal</code>]] module provides support for fast correctly-rounded
+
 
decimal floating point arithmetic. It offers several advantages over the
+
-----
[[../functions#float|<code>float</code>]] datatype:
+
 
 +
[[#module-decimal|decimal]] 模块支持快速正确舍入的十进制浮点运算。 与 [[../functions#float|float]] 数据类型相比,它具有以下几个优点:
  
 
<ul>
 
<ul>
<li><p>Decimal &quot;is based on a floating-point model which was designed with people
+
<li><p>十进制“基于浮点模型,该模型是为人而设计的,并且必然具有最重要的指导原则——计算机必须提供一种与人们在学校学习的算术相同的算术。” – 摘自十进制算术规范。</p></li>
in mind, and necessarily has a paramount guiding principle -- computers must
+
<li><p>十进制数可以精确表示。 相比之下,像 <code>1.1</code> <code>2.2</code> 这样的数字在二进制浮点数中没有精确的表示。 最终用户通常不希望 <code>1.1 + 2.2</code> 显示为 <code>3.3000000000000003</code>,因为它与二进制浮点数一样。</p></li>
provide an arithmetic that works in the same way as the arithmetic that
+
<li><p>精确性延续到算术中。 在十进制浮点数中,<code>0.1 + 0.1 + 0.1 - 0.3</code> 正好等于零。 在二进制浮点中,结果是 <code>5.5511151231257827e-017</code>。 虽然接近于零,但差异阻止了可靠的相等性测试,并且差异可能会累积。 出于这个原因,十进制在具有严格等式不变量的会计应用程序中是首选。</p></li>
people learn at school.&quot; -- excerpt from the decimal arithmetic specification.</p></li>
+
<li><p>十进制模块包含重要位置的概念,因此 <code>1.30 + 1.20</code> <code>2.50</code>。 保留尾随零以指示重要性。 这是货币应用程序的惯用表示。 对于乘法,“教科书”方法使用被乘数中的所有数字。 例如,<code>1.3 * 1.2</code> 给出 <code>1.56</code>,而 <code>1.30 * 1.20</code> 给出 <code>1.5600</code></p></li>
<li><p>Decimal numbers can be represented exactly. In contrast, numbers like
+
<li><p>与基于硬件的二进制浮点数不同,decimal 模块具有用户可更改的精度(默认为 28 位),该精度可以根据给定问题的需要而定:</p>
<code>1.1</code> and <code>2.2</code> do not have exact representations in binary
 
floating point. End users typically would not expect <code>1.1 + 2.2</code> to display
 
as <code>3.3000000000000003</code> as it does with binary floating point.</p></li>
 
<li><p>The exactness carries over into arithmetic. In decimal floating point, <code>0.1 + 0.1 + 0.1 - 0.3</code> is exactly equal to zero. In binary floating point, the result
 
is <code>5.5511151231257827e-017</code>. While 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.</p></li>
 
<li><p>The decimal module incorporates a notion of significant places so that <code>1.30 + 1.20</code> is <code>2.50</code>. The trailing zero is kept to indicate significance.
 
This is the customary presentation for monetary applications. For
 
multiplication, the &quot;schoolbook&quot; approach uses all the figures in the
 
multiplicands. For instance, <code>1.3 * 1.2</code> gives <code>1.56</code> while <code>1.30 * 1.20</code> gives <code>1.5600</code>.</p></li>
 
<li><p>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:</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; from decimal import *
+
<syntaxhighlight lang="python">>>> from decimal import *
&gt;&gt;&gt; getcontext().prec = 6
+
>>> getcontext().prec = 6
&gt;&gt;&gt; Decimal(1) / Decimal(7)
+
>>> Decimal(1) / Decimal(7)
 
Decimal('0.142857')
 
Decimal('0.142857')
&gt;&gt;&gt; getcontext().prec = 28
+
>>> getcontext().prec = 28
&gt;&gt;&gt; Decimal(1) / Decimal(7)
+
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')</pre>
+
Decimal('0.1428571428571428571428571429')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p>Both binary and decimal floating point are implemented in terms of published
+
<li><p>二进制和十进制浮点数都是根据已发布的标准实现的。 虽然内置 float 类型仅公开了其功能的一小部分,但 decimal 模块公开了标准的所有必需部分。 需要时,程序员可以完全控制舍入和信号处理。 这包括通过使用异常来阻止任何不精确操作来强制执行精确算术的选项。</p></li>
standards. While the built-in float type exposes only a modest portion of its
+
<li><p>十进制模块旨在支持“无偏见的精确未舍入十进制算术(有时称为定点算术)和舍入浮点算术”。 – 摘自十进制算术规范。</p></li></ul>
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.</p></li>
 
<li><p>The decimal module was designed to support &quot;without prejudice, both exact
 
unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
 
and rounded floating-point arithmetic.&quot; -- excerpt from the decimal
 
arithmetic specification.</p></li></ul>
 
  
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
+
十进制数是不可变的。 它有一个符号、系数数字和一个指数。 为了保持显着性,系数数字不会截断尾随零。 小数还包括特殊值,例如 <code>Infinity</code><code>-Infinity</code> <code>NaN</code>。 该标准还将 <code>-0</code> <code>+0</code> 区分开来。
exponent. To preserve significance, the coefficient digits do not truncate
 
trailing zeros. Decimals also include special values such as
 
<code>Infinity</code>, <code>-Infinity</code>, and <code>NaN</code>. The standard also
 
differentiates <code>-0</code> from <code>+0</code>.
 
  
The context for arithmetic is an environment specifying precision, rounding
+
算术的上下文是指定精度、舍入规则、指数限制、指示运算结果的标志以及确定信号是否被视为异常的陷阱启动器的环境。 舍入选项包括 [[#decimal.ROUND_CEILING|ROUND_CEILING]][[#decimal.ROUND_DOWN|ROUND_DOWN]][[#decimal.ROUND_FLOOR|ROUND_FLOOR]][[#decimal.ROUND_HALF_DOWN|ROUND_HALF_DOWN]]、ROUND_HALF_X64X1X1X1X14 、[[#decimal.ROUND_UP|ROUND_UP]] [[#decimal.ROUND_05UP|ROUND_05UP]]
rules, limits on exponents, flags indicating the results of operations, and trap
 
enablers which determine whether signals are treated as exceptions. Rounding
 
options include [[#decimal.ROUND_CEILING|<code>ROUND_CEILING</code>]], [[#decimal.ROUND_DOWN|<code>ROUND_DOWN</code>]],
 
[[#decimal.ROUND_FLOOR|<code>ROUND_FLOOR</code>]], [[#decimal.ROUND_HALF_DOWN|<code>ROUND_HALF_DOWN</code>]], [[#decimal.ROUND_HALF_EVEN|<code>ROUND_HALF_EVEN</code>]],
 
[[#decimal.ROUND_HALF_UP|<code>ROUND_HALF_UP</code>]], [[#decimal.ROUND_UP|<code>ROUND_UP</code>]], and [[#decimal.ROUND_05UP|<code>ROUND_05UP</code>]].
 
  
Signals are groups of exceptional conditions arising during the course of
+
信号是在计算过程中出现的一组异常情况。 根据应用程序的需要,信号可能会被忽略,被视为信息,或被视为异常。 十进制模块中的信号有:[[#decimal.Clamped|Clamped]][[#decimal.InvalidOperation|InvalidOperation]][[#decimal.DivisionByZero|DivisionByZero]][[#decimal.Inexact|Inexact]][[#decimal.Rounded|Rounded、]] ]次正常、[[#decimal.Overflow|溢出]][[#decimal.Underflow|下溢]][[#decimal.FloatOperation|FloatOperation]]
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: [[#decimal.Clamped|<code>Clamped</code>]], [[#decimal.InvalidOperation|<code>InvalidOperation</code>]],
 
[[#decimal.DivisionByZero|<code>DivisionByZero</code>]], [[#decimal.Inexact|<code>Inexact</code>]], [[#decimal.Rounded|<code>Rounded</code>]], [[#decimal.Subnormal|<code>Subnormal</code>]],
 
[[#decimal.Overflow|<code>Overflow</code>]], [[#decimal.Underflow|<code>Underflow</code>]] and [[#decimal.FloatOperation|<code>FloatOperation</code>]].
 
  
For each signal there is a flag and a trap enabler. When a signal is
+
对于每个信号,都有一个标志和一个陷阱使能器。 当遇到信号时,其标志设置为 1,然后,如果陷阱启用器设置为 1,则会引发异常。 标志是粘性的,因此用户需要在监视计算之前重置它们。
encountered, its flag is set to one, then, if the trap enabler is
 
set to one, an exception is raised. Flags are sticky, so the user needs to
 
reset them before monitoring a calculation.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
* IBM's General Decimal Arithmetic Specification, [http://speleotrove.com/decimal/decarith.html The General Decimal Arithmetic Specification].
+
* IBM 的通用十进制算术规范,[http://speleotrove.com/decimal/decarith.html 通用十进制算术规范]
  
  
第96行: 第57行:
  
 
<span id="decimal-tutorial"></span>
 
<span id="decimal-tutorial"></span>
== Quick-start Tutorial ==
+
== 快速入门教程 ==
  
The usual start to using decimals is importing the module, viewing the current
+
使用小数的通常开始是导入模块,使用 [[#decimal.getcontext|getcontext()]] 查看当前上下文,并在必要时为精度、舍入或启用陷阱设置新值:
context with [[#decimal.getcontext|<code>getcontext()</code>]] and, if necessary, setting new values for
 
precision, rounding, or enabled traps:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第106行: 第65行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; from decimal import *
+
<syntaxhighlight lang="python3">>>> from decimal import *
&gt;&gt;&gt; getcontext()
+
>>> getcontext()
 
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
 
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
 
         capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
 
         capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
 
         InvalidOperation])
 
         InvalidOperation])
  
&gt;&gt;&gt; getcontext().prec = 7      # Set a new precision</pre>
+
>>> getcontext().prec = 7      # Set a new precision</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Decimal instances can be constructed from integers, strings, floats, or tuples.
+
Decimal 实例可以由整数、字符串、浮点数或元组构成。 从整数或浮点数构造执行该整数或浮点数的值的精确转换。 十进制数包括特殊值,例如代表“非数字”的 <code>NaN</code>、正负 <code>Infinity</code> <code>-0</code>
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
 
<code>NaN</code> which stands for &quot;Not a number&quot;, positive and negative
 
<code>Infinity</code>, and <code>-0</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第127行: 第82行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 28
+
<syntaxhighlight lang="python3">>>> getcontext().prec = 28
&gt;&gt;&gt; Decimal(10)
+
>>> Decimal(10)
 
Decimal('10')
 
Decimal('10')
&gt;&gt;&gt; Decimal('3.14')
+
>>> Decimal('3.14')
 
Decimal('3.14')
 
Decimal('3.14')
&gt;&gt;&gt; Decimal(3.14)
+
>>> Decimal(3.14)
 
Decimal('3.140000000000000124344978758017532527446746826171875')
 
Decimal('3.140000000000000124344978758017532527446746826171875')
&gt;&gt;&gt; Decimal((0, (3, 1, 4), -2))
+
>>> Decimal((0, (3, 1, 4), -2))
 
Decimal('3.14')
 
Decimal('3.14')
&gt;&gt;&gt; Decimal(str(2.0 ** 0.5))
+
>>> Decimal(str(2.0 ** 0.5))
 
Decimal('1.4142135623730951')
 
Decimal('1.4142135623730951')
&gt;&gt;&gt; Decimal(2) ** Decimal('0.5')
+
>>> Decimal(2) ** Decimal('0.5')
 
Decimal('1.414213562373095048801688724')
 
Decimal('1.414213562373095048801688724')
&gt;&gt;&gt; Decimal('NaN')
+
>>> Decimal('NaN')
 
Decimal('NaN')
 
Decimal('NaN')
&gt;&gt;&gt; Decimal('-Infinity')
+
>>> Decimal('-Infinity')
Decimal('-Infinity')</pre>
+
Decimal('-Infinity')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If the [[#decimal.FloatOperation|<code>FloatOperation</code>]] signal is trapped, accidental mixing of
+
如果 [[#decimal.FloatOperation|FloatOperation]] 信号被捕获,构造函数中小数和浮点数的意外混合或排序比较会引发异常:
decimals and floats in constructors or ordering comparisons raises
 
an exception:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第156行: 第109行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = getcontext()
+
<syntaxhighlight lang="python3">>>> c = getcontext()
&gt;&gt;&gt; c.traps[FloatOperation] = True
+
>>> c.traps[FloatOperation] = True
&gt;&gt;&gt; Decimal(3.14)
+
>>> Decimal(3.14)
 
Traceback (most recent call last):
 
Traceback (most recent call last):
   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
+
   File "<stdin>", line 1, in <module>
decimal.FloatOperation: [&lt;class 'decimal.FloatOperation'&gt;]
+
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
&gt;&gt;&gt; Decimal('3.5') &lt; 3.7
+
>>> Decimal('3.5') < 3.7
 
Traceback (most recent call last):
 
Traceback (most recent call last):
   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
+
   File "<stdin>", line 1, in <module>
decimal.FloatOperation: [&lt;class 'decimal.FloatOperation'&gt;]
+
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
&gt;&gt;&gt; Decimal('3.5') == 3.5
+
>>> Decimal('3.5') == 3.5
True</pre>
+
True</syntaxhighlight>
  
 
</div>
 
</div>
第174行: 第127行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.3 新版功能.</span>
+
<span class="versionmodified added">3.3 版中的新功能。</span>
  
  
 
</div>
 
</div>
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.
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第186行: 第137行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 6
+
<pre class="pycon3">&gt;&gt;&gt; getcontext().prec = 6
 
&gt;&gt;&gt; Decimal('3.0')
 
&gt;&gt;&gt; Decimal('3.0')
 
Decimal('3.0')
 
Decimal('3.0')
第200行: 第151行:
  
 
</div>
 
</div>
If the internal limits of the C version are exceeded, constructing
+
如果超出 C 版本的内部限制,则构造一个小数会引发 [[#decimal.InvalidOperation|InvalidOperation]]
a decimal raises [[#decimal.InvalidOperation|<code>InvalidOperation</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第207行: 第157行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal(&quot;1e9999999999999999999&quot;)
+
<syntaxhighlight lang="python3">>>> Decimal("1e9999999999999999999")
 
Traceback (most recent call last):
 
Traceback (most recent call last):
   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
+
   File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [&lt;class 'decimal.InvalidOperation'&gt;]</pre>
+
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]</syntaxhighlight>
  
 
</div>
 
</div>
第217行: 第167行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<span class="versionmodified changed">在 3.3 版更改.</span>
+
<span class="versionmodified changed">在 3.3 版中更改。</span>
  
  
 
</div>
 
</div>
Decimals interact well with much of the rest of Python. Here is a small decimal
+
Decimals 可以与 Python 的其他大部分内容很好地交互。 这是一个小十进制浮点飞行马戏团:
floating point flying circus:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第228行: 第177行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
+
<pre class="pycon3">&gt;&gt;&gt; data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
 
&gt;&gt;&gt; max(data)
 
&gt;&gt;&gt; max(data)
 
Decimal('9.25')
 
Decimal('9.25')
第257行: 第206行:
  
 
</div>
 
</div>
And some mathematical functions are also available to Decimal:
+
一些数学函数也可用于 Decimal:
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第263行: 第212行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 28
+
<syntaxhighlight lang="python">>>> getcontext().prec = 28
&gt;&gt;&gt; Decimal(2).sqrt()
+
>>> Decimal(2).sqrt()
 
Decimal('1.414213562373095048801688724')
 
Decimal('1.414213562373095048801688724')
&gt;&gt;&gt; Decimal(1).exp()
+
>>> Decimal(1).exp()
 
Decimal('2.718281828459045235360287471')
 
Decimal('2.718281828459045235360287471')
&gt;&gt;&gt; Decimal('10').ln()
+
>>> Decimal('10').ln()
 
Decimal('2.302585092994045684017991455')
 
Decimal('2.302585092994045684017991455')
&gt;&gt;&gt; Decimal('10').log10()
+
>>> Decimal('10').log10()
Decimal('1')</pre>
+
Decimal('1')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The <code>quantize()</code> method rounds a number to a fixed exponent. This method is
+
<code>quantize()</code> 方法将数字四舍五入为固定指数。 此方法对于经常将结果四舍五入到固定数量位置的货币应用程序很有用:
useful for monetary applications that often round results to a fixed number of
 
places:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第284行: 第231行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
+
<syntaxhighlight lang="python">>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
 
Decimal('7.32')
 
Decimal('7.32')
&gt;&gt;&gt; Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
+
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')</pre>
+
Decimal('8')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As shown above, the [[#decimal.getcontext|<code>getcontext()</code>]] function accesses the current context and
+
如上所示,[[#decimal.getcontext|getcontext()]] 函数访问当前上下文并允许更改设置。 这种方法可以满足大多数应用程序的需求。
allows the settings to be changed. This approach meets the needs of most
 
applications.
 
  
For more advanced work, it may be useful to create alternate contexts using the
+
对于更高级的工作,使用 Context() 构造函数创建备用上下文可能很有用。 要激活备用,请使用 [[#decimal.setcontext|setcontext()]] 函数。
Context() constructor. To make an alternate active, use the [[#decimal.setcontext|<code>setcontext()</code>]]
 
function.
 
  
In accordance with the standard, the [[#module-decimal|<code>decimal</code>]] module provides two ready to
+
根据标准,[[#module-decimal|decimal]] 模块提供了两个随时可用的标准上下文,[[#decimal.BasicContext|BasicContext]] [[#decimal.ExtendedContext|ExtendedContext]]。 前者对于调试特别有用,因为许多陷阱都已启用:
use standard contexts, [[#decimal.BasicContext|<code>BasicContext</code>]] and [[#decimal.ExtendedContext|<code>ExtendedContext</code>]]. The
 
former is especially useful for debugging because many of the traps are
 
enabled:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第309行: 第249行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
+
<pre class="pycon3">&gt;&gt;&gt; myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
 
&gt;&gt;&gt; setcontext(myothercontext)
 
&gt;&gt;&gt; setcontext(myothercontext)
 
&gt;&gt;&gt; Decimal(1) / Decimal(7)
 
&gt;&gt;&gt; Decimal(1) / Decimal(7)
第333行: 第273行:
  
 
</div>
 
</div>
Contexts also have signal flags for monitoring exceptional conditions
+
上下文还具有用于监视计算过程中遇到的异常情况的信号标志。 标志保持设置直到明确清除,因此最好在每组受监控计算之前使用 <code>clear_flags()</code> 方法清除标志。
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 <code>clear_flags()</code> method.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第342行: 第279行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; setcontext(ExtendedContext)
+
<syntaxhighlight lang="python3">>>> setcontext(ExtendedContext)
&gt;&gt;&gt; getcontext().clear_flags()
+
>>> getcontext().clear_flags()
&gt;&gt;&gt; Decimal(355) / Decimal(113)
+
>>> Decimal(355) / Decimal(113)
 
Decimal('3.14159292')
 
Decimal('3.14159292')
&gt;&gt;&gt; getcontext()
+
>>> getcontext()
 
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
 
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
         capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])</pre>
+
         capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The ''flags'' entry shows that the rational approximation to <code>Pi</code> was
+
''flags'' 条目显示 <code>Pi</code> 的有理近似值被四舍五入(超出上下文精度的数字被丢弃)并且结果不准确(一些被丢弃的数字是非零的) .
rounded (digits beyond the context precision were thrown away) and that the
 
result is inexact (some of the discarded digits were non-zero).
 
  
Individual traps are set using the dictionary in the <code>traps</code> field of a
+
使用上下文的 <code>traps</code> 字段中的字典设置单个陷阱:
context:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第364行: 第298行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; setcontext(ExtendedContext)
+
<pre class="pycon3">&gt;&gt;&gt; setcontext(ExtendedContext)
 
&gt;&gt;&gt; Decimal(1) / Decimal(0)
 
&gt;&gt;&gt; Decimal(1) / Decimal(0)
 
Decimal('Infinity')
 
Decimal('Infinity')
第377行: 第311行:
  
 
</div>
 
</div>
Most programs adjust the current context only once, at the beginning of the
+
大多数程序仅在程序开始时调整当前上下文一次。 而且,在许多应用程序中,通过在循环内进行一次强制转换,数据会被转换为 [[#decimal.Decimal|Decimal]]。 创建上下文集和小数后,程序的大部分处理数据与其他 Python 数字类型没有什么不同。
program. And, in many applications, data is converted to [[#decimal.Decimal|<code>Decimal</code>]] with
 
a single cast inside a loop. With context set and decimals created, the bulk of
 
the program manipulates the data no differently than with other Python numeric
 
types.
 
  
  
第388行: 第318行:
  
 
<span id="decimal-decimal"></span>
 
<span id="decimal-decimal"></span>
== Decimal objects ==
+
== 十进制对象 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Decimal</code><span class="sig-paren">(</span>''<span class="n">value</span><span class="o">=</span><span class="default_value">'0'</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Decimal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'0'</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Construct a new [[#decimal.Decimal|<code>Decimal</code>]] object based from ''value''.</p>
+
<dd><p>根据 ''值'' 构造一个新的 [[#decimal.Decimal|Decimal]] 对象。</p>
<p>''value'' can be an integer, string, tuple, [[../functions#float|<code>float</code>]], or another [[#decimal.Decimal|<code>Decimal</code>]]
+
<p>''value'' 可以是整数、字符串、元组、[[../functions#float|float]] 或另一个 [[#decimal.Decimal|Decimal]] 对象。 如果没有给出 ''value'',则返回 <code>Decimal('0')</code>。 如果 ''value'' 是一个字符串,它应该在去除前导和尾随空格字符以及整个下划线后符合十进制数字字符串语法:</p>
object. If no ''value'' is given, returns <code>Decimal('0')</code>. 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:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>sign          ::=  '+' | '-'
+
<syntaxhighlight lang="python3">sign          ::=  '+' | '-'
 
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
 
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
 
indicator      ::=  'e' | 'E'
 
indicator      ::=  'e' | 'E'
第410行: 第337行:
 
nan            ::=  'NaN' [digits] | 'sNaN' [digits]
 
nan            ::=  'NaN' [digits] | 'sNaN' [digits]
 
numeric-value  ::=  decimal-part [exponent-part] | infinity
 
numeric-value  ::=  decimal-part [exponent-part] | infinity
numeric-string ::=  [sign] numeric-value | [sign] nan</pre>
+
numeric-string ::=  [sign] numeric-value | [sign] nan</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Other Unicode decimal digits are also permitted where <code>digit</code>
+
<p><code>digit</code> 出现在上面的地方也允许使用其他 Unicode 十进制数字。 这些包括来自各种其他字母表的十进制数字(例如,阿拉伯-印度语和梵文数字)以及全角数字 <code>'\uff10'</code> <code>'\uff19'</code></p>
appears above. These include decimal digits from various other
+
<p>如果 ''value'' 是一个 [[../stdtypes#tuple|元组]] ,它应该具有三个分量,一个符号(<code>0</code> 为正或 <code>1</code> 为负),一个 [[../stdtypes#tuple|元组]] 的数字和整数指数。 例如,<code>Decimal((0, (1, 4, 1, 4), -3))</code> 返回 <code>Decimal('1.414')</code></p>
alphabets (for example, Arabic-Indic and Devanāgarī digits) along
+
<p>如果 ''value'' [[../functions#float|float]],则二进制浮点值将无损地转换为其精确的十进制等效值。 这种转换通常需要 53 位或更多位的精度。 例如,<code>Decimal(float('1.1'))</code> 转换为 <code>Decimal('1.100000000000000088817841970012523233890533447265625')</code></p>
with the fullwidth digits <code>'\uff10'</code> through <code>'\uff19'</code>.</p>
+
<p>''context'' 精度不影响存储的位数。 这完全由 '''' 中的位数决定。 例如,即使上下文精度只有三个,<code>Decimal('3.00000')</code> 也会记录所有五个零。</p>
<p>If ''value'' is a [[../stdtypes#tuple|<code>tuple</code>]], it should have three components, a sign
+
<p>''context'' 参数的目的是确定如果 ''value'' 是格式错误的字符串,该怎么办。 如果上下文捕获 [[#decimal.InvalidOperation|InvalidOperation]],则会引发异常; 否则,构造函数返回一个新的 Decimal,其值为 <code>NaN</code></p>
(<code>0</code> for positive or <code>1</code> for negative), a [[../stdtypes#tuple|<code>tuple</code>]] of
+
<p>一旦构造,[[#decimal.Decimal|Decimal]] 对象是不可变的。</p>
digits, and an integer exponent. For example, <code>Decimal((0, (1, 4, 1, 4), -3))</code>
 
returns <code>Decimal('1.414')</code>.</p>
 
<p>If ''value'' is a [[../functions#float|<code>float</code>]], the binary floating point value is losslessly
 
converted to its exact decimal equivalent. This conversion can often require
 
53 or more digits of precision. For example, <code>Decimal(float('1.1'))</code>
 
converts to
 
<code>Decimal('1.100000000000000088817841970012523233890533447265625')</code>.</p>
 
<p>The ''context'' precision does not affect how many digits are stored. That is
 
determined exclusively by the number of digits in ''value''. For example,
 
<code>Decimal('3.00000')</code> records all five zeros even if the context precision is
 
only three.</p>
 
<p>The purpose of the ''context'' argument is determining what to do if ''value'' is a
 
malformed string. If the context traps [[#decimal.InvalidOperation|<code>InvalidOperation</code>]], an exception
 
is raised; otherwise, the constructor returns a new Decimal with the value of
 
<code>NaN</code>.</p>
 
<p>Once constructed, [[#decimal.Decimal|<code>Decimal</code>]] objects are immutable.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.2 版更改: </span>The argument to the constructor is now permitted to be a [[../functions#float|<code>float</code>]]
+
<p><span class="versionmodified changed"> 3.2 版更改: </span> 现在允许构造函数的参数是 [[../functions#float|float]] 实例。</p>
instance.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.3 版更改: </span>[[../functions#float|<code>float</code>]] arguments raise an exception if the [[#decimal.FloatOperation|<code>FloatOperation</code>]]
+
<p><span class="versionmodified changed"> 在 3.3 版中更改:如果设置了 [[#decimal.FloatOperation|FloatOperation]] 陷阱,则 </span>[[../functions#float|float]] 参数会引发异常。 默认情况下,陷阱是关闭的。</p>
trap is set. By default the trap is off.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>Underscores are allowed for grouping, as with integral and floating-point
+
<p><span class="versionmodified changed"> 3.6 版更改: </span> 允许使用下划线进行分组,就像代码中的整数和浮点文字一样。</p>
literals in code.</p>
 
  
 
</div>
 
</div>
<p>Decimal floating point objects share many properties with the other built-in
+
<p>十进制浮点对象与其他内置数字类型共享许多属性,例如 [[../functions#float|float]] [[../functions#int|int]]。 所有常用的数学运算和特殊方法都适用。 同样,十进制对象可以被复制、腌制、打印、用作字典键、用作集合元素、比较、排序和强制转换为另一种类型(例如 [[../functions#float|float]] [[../functions#int|int]].</p>
numeric types such as [[../functions#float|<code>float</code>]] and [[../functions#int|<code>int</code>]]. All of the usual math
+
<p>Decimal 对象的算术与整数和浮点数的算术之间存在一些细微差别。 当余数运算符 <code>%</code> 应用于 Decimal 对象时,结果的符号是 ''dividend'' 的符号而不是除数的符号:</p>
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 [[../functions#float|<code>float</code>]] or
 
[[../functions#int|<code>int</code>]]).</p>
 
<p>There are some small differences between arithmetic on Decimal objects and
 
arithmetic on integers and floats. When the remainder operator <code>%</code> is
 
applied to Decimal objects, the sign of the result is the sign of the
 
''dividend'' rather than the sign of the divisor:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; (-7) % 4
+
<syntaxhighlight lang="python3">>>> (-7) % 4
 
1
 
1
&gt;&gt;&gt; Decimal(-7) % Decimal(4)
+
>>> Decimal(-7) % Decimal(4)
Decimal('-3')</pre>
+
Decimal('-3')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The integer division operator <code>//</code> behaves analogously, returning the
+
<p>整数除法运算符 <code>//</code> 的行为类似,返回真商的整数部分(向零截断)而不是其底,以保留通常的恒等式 <code>x == (x // y) * y + x % y</code></p>
integer part of the true quotient (truncating towards zero) rather than its
 
floor, so as to preserve the usual identity <code>x == (x // y) * y + x % y</code>:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; -7 // 4
+
<syntaxhighlight lang="python3">>>> -7 // 4
 
-2
 
-2
&gt;&gt;&gt; Decimal(-7) // Decimal(4)
+
>>> Decimal(-7) // Decimal(4)
Decimal('-1')</pre>
+
Decimal('-1')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The <code>%</code> and <code>//</code> operators implement the <code>remainder</code> and
+
<p><code>%</code> <code>//</code> 运算符实现了 <code>remainder</code> <code>divide-integer</code> 操作(分别),如规范中所述。</p>
<code>divide-integer</code> operations (respectively) as described in the
+
<p>在算术运算中,小数对象通常不能与浮点数或 [[../fractions#fractions|fractions.Fraction]] 的实例组合:例如,尝试将 [[#decimal.Decimal|Decimal]] 添加到 [[../functions#float|float]] 将引发 [[../exceptions#TypeError|TypeError]]。 但是,可以使用 Python 的比较运算符将 [[#decimal.Decimal|Decimal]] 实例 <code>x</code> 与另一个数字 <code>y</code> 进行比较。 这避免了在不同类型的数字之间进行相等比较时的混淆结果。</p>
specification.</p>
 
<p>Decimal objects cannot generally be combined with floats or
 
instances of [[../fractions#fractions|<code>fractions.Fraction</code>]] in arithmetic operations:
 
an attempt to add a [[#decimal.Decimal|<code>Decimal</code>]] to a [[../functions#float|<code>float</code>]], for
 
example, will raise a [[../exceptions#TypeError|<code>TypeError</code>]]. However, it is possible to
 
use Python's comparison operators to compare a [[#decimal.Decimal|<code>Decimal</code>]]
 
instance <code>x</code> with another number <code>y</code>. This avoids confusing results
 
when doing equality comparisons between numbers of different types.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.2 版更改: </span>Mixed-type comparisons between [[#decimal.Decimal|<code>Decimal</code>]] instances and other
+
<p><span class="versionmodified changed"> 3.2 版更改: </span> 现在完全支持 [[#decimal.Decimal|Decimal]] 实例和其他数字类型之间的混合类型比较。</p>
numeric types are now fully supported.</p>
 
  
 
</div>
 
</div>
<p>In addition to the standard numeric properties, decimal floating point
+
<p>除了标准的数字属性之外,十进制浮点对象还有许多专门的方法:</p>
objects also have a number of specialized methods:</p>
 
 
<dl>
 
<dl>
<dt><code>adjusted</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">adjusted</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the adjusted exponent after shifting out the coefficient's
+
<dd><p>在移出系数最右边的数字后返回调整后的指数,直到只剩下前导数字:<code>Decimal('321e+5').adjusted()</code> 返回七。 用于确定最高有效数字相对于小数点的位置。</p></dd></dl>
rightmost digits until only the lead digit remains:
 
<code>Decimal('321e+5').adjusted()</code> returns seven. Used for determining the
 
position of the most significant digit with respect to the decimal point.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>as_integer_ratio</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">as_integer_ratio</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return a pair <code>(n, d)</code> of integers that represent the given
+
<dd><p>返回一对 <code>(n, d)</code> 整数,这些整数将给定的 [[#decimal.Decimal|Decimal]] 实例表示为分数,以最低项和正分母表示:</p>
[[#decimal.Decimal|<code>Decimal</code>]] instance as a fraction, in lowest terms and
 
with a positive denominator:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal('-3.14').as_integer_ratio()
+
<syntaxhighlight lang="python3">>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)</pre>
+
(-157, 50)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The conversion is exact. Raise OverflowError on infinities and ValueError
+
<p>转换是准确的。 在无穷大上引发 OverflowError 并在 NaN 上引发 ValueError。</p></dd></dl>
on NaNs.</p></dd></dl>
 
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.6 新版功能.</span></p>
+
<p><span class="versionmodified added">3.6 版中的新功能。</span></p>
  
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt><code>as_tuple</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">as_tuple</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return a [[../../glossary#term-named-tuple|<span class="xref std std-term">named tuple</span>]] representation of the number:
+
<dd><p>返回数字的 [[../../glossary#term-named-tuple|命名元组]] 表示:<code>DecimalTuple(sign, digits, exponent)</code></p></dd></dl>
<code>DecimalTuple(sign, digits, exponent)</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>canonical</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">canonical</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the canonical encoding of the argument. Currently, the encoding of
+
<dd><p>返回参数的规范编码。 目前,[[#decimal.Decimal|Decimal]] 实例的编码始终是规范的,因此此操作返回其参数不变。</p></dd></dl>
a [[#decimal.Decimal|<code>Decimal</code>]] instance is always canonical, so this operation returns
 
its argument unchanged.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>compare</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compare the values of two Decimal instances. [[#decimal.Decimal.compare|<code>compare()</code>]] returns a
+
<dd><p>比较两个 Decimal 实例的值。 [[#decimal.Decimal.compare|compare()]] 返回一个 Decimal 实例,如果任一操作数为 NaN,则结果为 NaN:</p>
Decimal instance, and if either operand is a NaN then the result is a
 
NaN:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>a or b is a NaN  ==&gt; Decimal('NaN')
+
<syntaxhighlight lang="python3">a or b is a NaN  ==> Decimal('NaN')
a &lt; b            ==&gt; Decimal('-1')
+
a < b            ==> Decimal('-1')
a == b          ==&gt; Decimal('0')
+
a == b          ==> Decimal('0')
a &gt; b            ==&gt; Decimal('1')</pre>
+
a > b            ==> Decimal('1')</syntaxhighlight>
  
 
</div>
 
</div>
第570行: 第447行:
  
 
<dl>
 
<dl>
<dt><code>compare_signal</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare_signal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>This operation is identical to the [[#decimal.Decimal.compare|<code>compare()</code>]] method, except that all
+
<dd><p>此操作与 [[#decimal.Decimal.compare|compare()]] 方法相同,只是所有 NaN 都发出信号。 也就是说,如果两个操作数都不是信号 NaN,则任何安静的 NaN 操作数都被视为信号 NaN。</p></dd></dl>
NaNs signal. That is, if neither operand is a signaling NaN then any
 
quiet NaN operand is treated as though it were a signaling NaN.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>compare_total</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare_total</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compare two operands using their abstract representation rather than their
+
<dd><p>使用它们的抽象表示而不是它们的数值比较两个操作数。 类似于 [[#decimal.Decimal.compare|compare()]] 方法,但结果给出了 [[#decimal.Decimal|Decimal]] 实例的总排序。 具有相同数值但不同表示形式的两个 [[#decimal.Decimal|Decimal]] 实例在此排序中比较不相等:</p>
numerical value. Similar to the [[#decimal.Decimal.compare|<code>compare()</code>]] method, but the result
 
gives a total ordering on [[#decimal.Decimal|<code>Decimal</code>]] instances. Two
 
[[#decimal.Decimal|<code>Decimal</code>]] instances with the same numeric value but different
 
representations compare unequal in this ordering:</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal('12.0').compare_total(Decimal('12'))
+
<syntaxhighlight lang="python">>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')</pre>
+
Decimal('-1')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Quiet and signaling NaNs are also included in the total ordering. The
+
<p>Quiet 和 Signaling NaN 也包含在总排序中。 如果两个操作数具有相同的表示形式,则此函数的结果为 <code>Decimal('0')</code>,如果第一个操作数在总顺序中低于第二个,则为 <code>Decimal('-1')</code>,如果第一个操作数的顺序为 <code>Decimal('1')</code>操作数的总顺序高于第二个操作数。 有关总订单的详细信息,请参阅规范。</p>
result of this function is <code>Decimal('0')</code> if both operands have the same
+
<p>此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。</p></dd></dl>
representation, <code>Decimal('-1')</code> if the first operand is lower in the
 
total order than the second, and <code>Decimal('1')</code> if the first operand is
 
higher in the total order than the second operand. See the specification
 
for details of the total order.</p>
 
<p>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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>compare_total_mag</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare_total_mag</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compare two operands using their abstract representation rather than their
+
<dd><p>使用它们的抽象表示而不是它们的值来比较两个操作数,如 [[#decimal.Decimal.compare_total|compare_total()]],但忽略每个操作数的符号。 <code>x.compare_total_mag(y)</code> 相当于 <code>x.copy_abs().compare_total(y.copy_abs())</code></p>
value as in [[#decimal.Decimal.compare_total|<code>compare_total()</code>]], but ignoring the sign of each operand.
+
<p>此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。</p></dd></dl>
<code>x.compare_total_mag(y)</code> is equivalent to
 
<code>x.copy_abs().compare_total(y.copy_abs())</code>.</p>
 
<p>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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>conjugate</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">conjugate</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Just returns self, this method is only to comply with the Decimal
+
<dd><p>只返回self,此方法仅符合Decimal Specification。</p></dd></dl>
Specification.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>copy_abs</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_abs</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the absolute value of the argument. This operation is unaffected
+
<dd><p>返回参数的绝对值。 此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。</p></dd></dl>
by the context and is quiet: no flags are changed and no rounding is
 
performed.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>copy_negate</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_negate</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the negation of the argument. This operation is unaffected by the
+
<dd><p>返回参数的否定。 此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。</p></dd></dl>
context and is quiet: no flags are changed and no rounding is performed.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>copy_sign</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_sign</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a copy of the first operand with the sign set to be the same as the
+
<dd><p>返回第一个操作数的副本,其符号设置为与第二个操作数的符号相同。 例如:</p>
sign of the second operand. For example:</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal('2.3').copy_sign(Decimal('-1.5'))
+
<syntaxhighlight lang="python">>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')</pre>
+
Decimal('-2.3')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>This operation is unaffected by context and is quiet: no flags are changed
+
<p>此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。</p></dd></dl>
and no rounding is performed. As an exception, the C version may raise
 
InvalidOperation if the second operand cannot be converted exactly.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>exp</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">exp</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the value of the (natural) exponential function <code>e**x</code> at the
+
<dd><p>返回给定数字的(自然)指数函数 <code>e**x</code> 的值。 结果使用 [[#decimal.ROUND_HALF_EVEN|ROUND_HALF_EVEN]] 舍入模式正确舍入。</p>
given number. The result is correctly rounded using the
 
[[#decimal.ROUND_HALF_EVEN|<code>ROUND_HALF_EVEN</code>]] rounding mode.</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal(1).exp()
+
<syntaxhighlight lang="python">>>> Decimal(1).exp()
 
Decimal('2.718281828459045235360287471')
 
Decimal('2.718281828459045235360287471')
&gt;&gt;&gt; Decimal(321).exp()
+
>>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139')</pre>
+
Decimal('2.561702493119680037517373933E+139')</syntaxhighlight>
  
 
</div>
 
</div>
第665行: 第515行:
  
 
<dl>
 
<dl>
<dt><code>from_float</code><span class="sig-paren">(</span>''<span class="n">f</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">from_float</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">f</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Classmethod that converts a float to a decimal number, exactly.</p>
+
<dd><p>准确地将浮点数转换为十进制数的类方法。</p>
<p>Note Decimal.from_float(0.1) is not the same as Decimal('0.1').
+
<p>注意 Decimal.from_float(0.1) Decimal('0.1') 不同。 由于 0.1 不能用二进制浮点精确表示,因此该值存储为最接近的可表示值,即 0x1.999999999999ap-4。 十进制的等效值是 0.1000000000000000055511151231257827021181583404541015625。</p>
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. That equivalent value in decimal is
 
0.1000000000000000055511151231257827021181583404541015625.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>From Python 3.2 onwards, a [[#decimal.Decimal|<code>Decimal</code>]] instance
+
<p>Python 3.2 开始,[[#decimal.Decimal|Decimal]] 实例也可以直接从 [[../functions#float|float]] 构造。</p>
can also be constructed directly from a [[../functions#float|<code>float</code>]].</p>
 
  
 
</div>
 
</div>
第683行: 第528行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal.from_float(0.1)
+
<pre class="pycon3">&gt;&gt;&gt; Decimal.from_float(0.1)
 
Decimal('0.1000000000000000055511151231257827021181583404541015625')
 
Decimal('0.1000000000000000055511151231257827021181583404541015625')
 
&gt;&gt;&gt; Decimal.from_float(float('nan'))
 
&gt;&gt;&gt; Decimal.from_float(float('nan'))
第697行: 第542行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.1 新版功能.</span></p>
+
<p><span class="versionmodified added">3.1 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>fma</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">third</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">fma</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">third</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Fused multiply-add. Return self*other+third with no rounding of the
+
<dd><p>融合乘加。 返回 self*other+third ,中间产品 self*other 没有四舍五入。</p>
intermediate product self*other.</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal(2).fma(3, 5)
+
<syntaxhighlight lang="python">>>> Decimal(2).fma(3, 5)
Decimal('11')</pre>
+
Decimal('11')</syntaxhighlight>
  
 
</div>
 
</div>
第717行: 第561行:
  
 
<dl>
 
<dl>
<dt><code>is_canonical</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_canonical</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is canonical and [[../constants#False|<code>False</code>]]
+
<dd><p>如果参数是规范的,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]。 目前,[[#decimal.Decimal|Decimal]] 实例总是规范的,所以这个操作总是返回 [[../constants#True|True]]</p></dd></dl>
otherwise. Currently, a [[#decimal.Decimal|<code>Decimal</code>]] instance is always canonical, so
 
this operation always returns [[../constants#True|<code>True</code>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_finite</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_finite</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is a finite number, and
+
<dd><p>如果参数是有限数,则返回 [[../constants#True|True]],如果参数是无穷大或 NaN,则返回 [[../constants#False|False]]</p></dd></dl>
[[../constants#False|<code>False</code>]] if the argument is an infinity or a NaN.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_infinite</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_infinite</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is either positive or negative
+
<dd><p>如果参数是正无穷大或负无穷大,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]</p></dd></dl>
infinity and [[../constants#False|<code>False</code>]] otherwise.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_nan</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_nan</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is a (quiet or signaling) NaN and
+
<dd><p>如果参数是(安静或信号)NaN,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]</p></dd></dl>
[[../constants#False|<code>False</code>]] otherwise.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_normal</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_normal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is a ''normal'' finite number. Return
+
<dd><p>如果参数是 ''normal'' 有限数,则返回 [[../constants#True|True]]。 如果参数为零、次正规、无穷大或 NaN,则返回 [[../constants#False|False]]</p></dd></dl>
[[../constants#False|<code>False</code>]] if the argument is zero, subnormal, infinite or a NaN.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_qnan</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_qnan</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is a quiet NaN, and
+
<dd><p>如果参数是安静的 NaN,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]</p></dd></dl>
[[../constants#False|<code>False</code>]] otherwise.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_signed</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_signed</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument has a negative sign and
+
<dd><p>如果参数有负号,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]。 请注意,零和 NaN 都可以带有符号。</p></dd></dl>
[[../constants#False|<code>False</code>]] otherwise. Note that zeros and NaNs can both carry signs.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_snan</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_snan</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is a signaling NaN and [[../constants#False|<code>False</code>]]
+
<dd><p>如果参数是信号 NaN,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]</p></dd></dl>
otherwise.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_subnormal</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_subnormal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is subnormal, and [[../constants#False|<code>False</code>]]
+
<dd><p>如果参数不正常,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]</p></dd></dl>
otherwise.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>is_zero</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_zero</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if the argument is a (positive or negative) zero and
+
<dd><p>如果参数是(正或负)零,则返回 [[../constants#True|True]],否则返回 [[../constants#False|False]]</p></dd></dl>
[[../constants#False|<code>False</code>]] otherwise.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>ln</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">ln</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the natural (base e) logarithm of the operand. The result is
+
<dd><p>返回操作数的自然(以 e 为底)对数。 结果使用 [[#decimal.ROUND_HALF_EVEN|ROUND_HALF_EVEN]] 舍入模式正确舍入。</p></dd></dl>
correctly rounded using the [[#decimal.ROUND_HALF_EVEN|<code>ROUND_HALF_EVEN</code>]] rounding mode.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>log10</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">log10</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the base ten logarithm of the operand. The result is correctly
+
<dd><p>返回操作数的以 10 为底的对数。 结果使用 [[#decimal.ROUND_HALF_EVEN|ROUND_HALF_EVEN]] 舍入模式正确舍入。</p></dd></dl>
rounded using the [[#decimal.ROUND_HALF_EVEN|<code>ROUND_HALF_EVEN</code>]] rounding mode.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>logb</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logb</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>For a nonzero number, return the adjusted exponent of its operand as a
+
<dd><p>对于非零数,将其操作数的调整指数作为 [[#decimal.Decimal|Decimal]] 实例返回。 如果操作数为零,则返回 <code>Decimal('-Infinity')</code> 并引发 [[#decimal.DivisionByZero|DivisionByZero]] 标志。 如果操作数是无穷大,则返回 <code>Decimal('Infinity')</code></p></dd></dl>
[[#decimal.Decimal|<code>Decimal</code>]] instance. If the operand is a zero then
 
<code>Decimal('-Infinity')</code> is returned and the [[#decimal.DivisionByZero|<code>DivisionByZero</code>]] flag
 
is raised. If the operand is an infinity then <code>Decimal('Infinity')</code> is
 
returned.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>logical_and</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_and</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>[[#decimal.Decimal.logical_and|<code>logical_and()</code>]] is a logical operation which takes two ''logical
+
<dd><p>[[#decimal.Decimal.logical_and|logical_and()]] 是一个逻辑运算,它采用两个 ''逻辑操作数'' (请参阅 [[#logical-operands-label|逻辑操作数]] )。 结果是两个操作数的数字 <code>and</code></p></dd></dl>
operands'' (see [[#logical-operands-label|<span class="std std-ref">Logical operands</span>]]). The result is the
 
digit-wise <code>and</code> of the two operands.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>logical_invert</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_invert</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>[[#decimal.Decimal.logical_invert|<code>logical_invert()</code>]] is a logical operation. The
+
<dd><p>[[#decimal.Decimal.logical_invert|logical_invert()]] 是逻辑运算。 结果是操作数的数字反转。</p></dd></dl>
result is the digit-wise inversion of the operand.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>logical_or</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_or</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>[[#decimal.Decimal.logical_or|<code>logical_or()</code>]] is a logical operation which takes two ''logical
+
<dd><p>[[#decimal.Decimal.logical_or|logical_or()]] 是一个逻辑运算,它采用两个 ''逻辑操作数'' (请参阅 [[#logical-operands-label|逻辑操作数]] )。 结果是两个操作数的数字 <code>or</code></p></dd></dl>
operands'' (see [[#logical-operands-label|<span class="std std-ref">Logical operands</span>]]). The result is the
 
digit-wise <code>or</code> of the two operands.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>logical_xor</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_xor</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>[[#decimal.Decimal.logical_xor|<code>logical_xor()</code>]] is a logical operation which takes two ''logical
+
<dd><p>[[#decimal.Decimal.logical_xor|logical_xor()]] 是一个逻辑运算,它采用两个 ''逻辑操作数'' (参见 [[#logical-operands-label|逻辑操作数]] )。 结果是两个操作数的逐位异或。</p></dd></dl>
operands'' (see [[#logical-operands-label|<span class="std std-ref">Logical operands</span>]]). The result is the
 
digit-wise exclusive or of the two operands.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>max</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">max</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Like <code>max(self, other)</code> except that the context rounding rule is applied
+
<dd><p><code>max(self, other)</code> 类似,除了在返回之前应用上下文舍入规则,并且 <code>NaN</code> 值要么发出信号要么忽略(取决于上下文以及它们是发出信号还是静默)。</p></dd></dl>
before returning and that <code>NaN</code> values are either signaled or
 
ignored (depending on the context and whether they are signaling or
 
quiet).</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>max_mag</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">max_mag</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Similar to the [[#decimal.Decimal.max|<code>max()</code>]] method, but the comparison is done using the
+
<dd><p>类似于 [[#decimal.Decimal.max|max()]] 方法,但比较是使用操作数的绝对值完成的。</p></dd></dl>
absolute values of the operands.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>min</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">min</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Like <code>min(self, other)</code> except that the context rounding rule is applied
+
<dd><p><code>min(self, other)</code> 类似,除了在返回之前应用上下文舍入规则,并且 <code>NaN</code> 值要么发出信号要么忽略(取决于上下文以及它们是发出信号还是静默)。</p></dd></dl>
before returning and that <code>NaN</code> values are either signaled or
 
ignored (depending on the context and whether they are signaling or
 
quiet).</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>min_mag</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">min_mag</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Similar to the [[#decimal.Decimal.min|<code>min()</code>]] method, but the comparison is done using the
+
<dd><p>类似于 [[#decimal.Decimal.min|min()]] 方法,但比较是使用操作数的绝对值完成的。</p></dd></dl>
absolute values of the operands.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>next_minus</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">next_minus</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the largest number representable in the given context (or in the
+
<dd><p>返回在给定上下文(如果没有给定上下文,则在当前线程的上下文)中小于给定操作数的最大可表示数。</p></dd></dl>
current thread's context if no context is given) that is smaller than the
 
given operand.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>next_plus</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">next_plus</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the smallest number representable in the given context (or in the
+
<dd><p>返回在给定上下文(如果没有给定上下文,则在当前线程的上下文)中大于给定操作数的可表示的最小数字。</p></dd></dl>
current thread's context if no context is given) that is larger than the
 
given operand.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>next_toward</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">next_toward</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>If the two operands are unequal, return the number closest to the first
+
<dd><p>如果两个操作数不相等,则返回在第二个操作数的方向上最接近第一个操作数的数字。 如果两个操作数在数值上相等,则返回第一个操作数的副本,其符号设置为与第二个操作数的符号相同。</p></dd></dl>
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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>normalize</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">normalize</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Normalize the number by stripping the rightmost trailing zeros and
+
<dd><p>通过去除最右边的尾随零并将等于 <code>Decimal('0')</code> 的任何结果转换为 <code>Decimal('0e0')</code> 来标准化数字。 用于为等价类的属性生成规范值。 例如,<code>Decimal('32.100')</code> <code>Decimal('0.321000e+2')</code> 都归一化为等效值 <code>Decimal('32.1')</code></p></dd></dl>
converting any result equal to <code>Decimal('0')</code> to
 
<code>Decimal('0e0')</code>. Used for producing canonical values for attributes
 
of an equivalence class. For example, <code>Decimal('32.100')</code> and
 
<code>Decimal('0.321000e+2')</code> both normalize to the equivalent value
 
<code>Decimal('32.1')</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>number_class</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">number_class</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a string describing the ''class'' of the operand. The returned value
+
<dd><p>返回描述操作数的 '''' 的字符串。 返回值是以下十个字符串之一。</p>
is one of the following ten strings.</p>
 
 
<ul>
 
<ul>
<li><p><code>&quot;-Infinity&quot;</code>, indicating that the operand is negative infinity.</p></li>
+
<li><p><code>&quot;-Infinity&quot;</code>,表示操作数为负无穷大。</p></li>
<li><p><code>&quot;-Normal&quot;</code>, indicating that the operand is a negative normal number.</p></li>
+
<li><p><code>&quot;-Normal&quot;</code>,表示操作数为负数。</p></li>
<li><p><code>&quot;-Subnormal&quot;</code>, indicating that the operand is negative and subnormal.</p></li>
+
<li><p><code>&quot;-Subnormal&quot;</code>,表示操作数为负数,次正规。</p></li>
<li><p><code>&quot;-Zero&quot;</code>, indicating that the operand is a negative zero.</p></li>
+
<li><p><code>&quot;-Zero&quot;</code>,表示操作数为负零。</p></li>
<li><p><code>&quot;+Zero&quot;</code>, indicating that the operand is a positive zero.</p></li>
+
<li><p><code>&quot;+Zero&quot;</code>,表示操作数为正零。</p></li>
<li><p><code>&quot;+Subnormal&quot;</code>, indicating that the operand is positive and subnormal.</p></li>
+
<li><p><code>&quot;+Subnormal&quot;</code>,表示操作数为正,次正规。</p></li>
<li><p><code>&quot;+Normal&quot;</code>, indicating that the operand is a positive normal number.</p></li>
+
<li><p><code>&quot;+Normal&quot;</code>,表示操作数为正数。</p></li>
<li><p><code>&quot;+Infinity&quot;</code>, indicating that the operand is positive infinity.</p></li>
+
<li><p><code>&quot;+Infinity&quot;</code>,表示操作数为正无穷大。</p></li>
<li><p><code>&quot;NaN&quot;</code>, indicating that the operand is a quiet NaN (Not a Number).</p></li>
+
<li><p><code>&quot;NaN&quot;</code>,表示操作数是一个安静的 NaN(Not a Number)。</p></li>
<li><p><code>&quot;sNaN&quot;</code>, indicating that the operand is a signaling NaN.</p></li></ul>
+
<li><p><code>&quot;sNaN&quot;</code>,表示操作数为信令NaN。</p></li></ul>
 
</dd></dl>
 
</dd></dl>
  
 
<dl>
 
<dl>
<dt><code>quantize</code><span class="sig-paren">(</span>''<span class="n">exp</span>'', ''<span class="n">rounding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">quantize</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">exp</span></span>'', ''<span class="n"><span class="pre">rounding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a value equal to the first operand after rounding and having the
+
<dd><p>在舍入并具有第二个操作数的指数后返回等于第一个操作数的值。</p>
exponent of the second operand.</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal('1.41421356').quantize(Decimal('1.000'))
+
<syntaxhighlight lang="python">>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')</pre>
+
Decimal('1.414')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Unlike other operations, if the length of the coefficient after the
+
<p>与其他操作不同,如果量化操作后系数的长度大于精度,则会发出 [[#decimal.InvalidOperation|InvalidOperation]] 信号。 这保证了除非出现错误条件,否则量化指数始终等于右侧操作数的指数。</p>
quantize operation would be greater than precision, then an
+
<p>同样与其他操作不同的是,量化从不发出下溢信号,即使结果不正常且不准确。</p>
[[#decimal.InvalidOperation|<code>InvalidOperation</code>]] is signaled. This guarantees that, unless there
+
<p>如果第二个操作数的指数大于第一个的指数,则可能需要舍入。 在这种情况下,舍入模式由 <code>rounding</code> 参数决定,否则由 <code>context</code> 参数决定; 如果两个参数都没有给出,则使用当前线程上下文的舍入模式。</p>
is an error condition, the quantized exponent is always equal to that of
+
<p>只要结果指数大于 <code>Emax</code> 或小于 <code>Etiny</code>,就会返回错误。</p></dd></dl>
the right-hand operand.</p>
 
<p>Also unlike other operations, quantize never signals Underflow, even if
 
the result is subnormal and inexact.</p>
 
<p>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 <code>rounding</code> argument if given, else by the given
 
<code>context</code> argument; if neither argument is given the rounding mode of
 
the current thread's context is used.</p>
 
<p>An error is returned whenever the resulting exponent is greater than
 
<code>Emax</code> or less than <code>Etiny</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>radix</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">radix</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return <code>Decimal(10)</code>, the radix (base) in which the [[#decimal.Decimal|<code>Decimal</code>]]
+
<dd><p>返回 <code>Decimal(10)</code>[[#decimal.Decimal|Decimal]] 类执行其所有算术的基数(基数)。 包括在内是为了与规范兼容。</p></dd></dl>
class does all its arithmetic. Included for compatibility with the
 
specification.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>remainder_near</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">remainder_near</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the remainder from dividing ''self'' by ''other''. This differs from
+
<dd><p>返回将 ''self'' 除以 ''other'' 的余数。 这与 <code>self % other</code> 的不同之处在于余数的符号被选择为使其绝对值最小。 更准确地说,返回值是 <code>self - n * other</code>,其中 <code>n</code> 是最接近 <code>self / other</code> 确切值的整数,如果两个整数相等,则选择偶数。</p>
<code>self % other</code> in that the sign of the remainder is chosen so as to
+
<p>如果结果为零,则其符号将是 ''self'' 的符号。</p>
minimize its absolute value. More precisely, the return value is
 
<code>self - n * other</code> where <code>n</code> is the integer nearest to the exact
 
value of <code>self / other</code>, and if two integers are equally near then the
 
even one is chosen.</p>
 
<p>If the result is zero then its sign will be the sign of ''self''.</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal(18).remainder_near(Decimal(10))
+
<syntaxhighlight lang="python">>>> Decimal(18).remainder_near(Decimal(10))
 
Decimal('-2')
 
Decimal('-2')
&gt;&gt;&gt; Decimal(25).remainder_near(Decimal(10))
+
>>> Decimal(25).remainder_near(Decimal(10))
 
Decimal('5')
 
Decimal('5')
&gt;&gt;&gt; Decimal(35).remainder_near(Decimal(10))
+
>>> Decimal(35).remainder_near(Decimal(10))
Decimal('-5')</pre>
+
Decimal('-5')</syntaxhighlight>
  
 
</div>
 
</div>
第937行: 第718行:
  
 
<dl>
 
<dl>
<dt><code>rotate</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">rotate</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the result of rotating the digits of the first operand by an amount
+
<dd><p>返回按第二个操作数指定的量旋转第一个操作数的数字的结果。 第二个操作数必须是从 -precision precision 范围内的整数。 第二个操作数的绝对值给出了要旋转的位置数。 如果第二个操作数为正,则向左旋转; 否则向右旋转。 如有必要,第一个操作数的系数在左侧填充零以达到长度精度。 第一个操作数的符号和指数不变。</p></dd></dl>
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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>same_quantum</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">same_quantum</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Test whether self and other have the same exponent or whether both are
+
<dd><p>测试 self other 是否具有相同的指数或两者是否都是 <code>NaN</code></p>
<code>NaN</code>.</p>
+
<p>此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。</p></dd></dl>
<p>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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>scaleb</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">scaleb</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the first operand with exponent adjusted by the second.
+
<dd><p>返回第一个操作数,其指数由第二个调整。 等效地,返回乘以 <code>10**other</code> 的第一个操作数。 第二个操作数必须是整数。</p></dd></dl>
Equivalently, return the first operand multiplied by <code>10**other</code>. The
 
second operand must be an integer.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>shift</code><span class="sig-paren">(</span>''<span class="n">other</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">shift</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">other</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the result of shifting the digits of the first operand by an amount
+
<dd><p>返回按第二个操作数指定的量移动第一个操作数的数字的结果。 第二个操作数必须是从 -precision precision 范围内的整数。 第二个操作数的绝对值给出了要移位的位数。 如果第二个操作数为正,则向左移位; 否则向右移动。 移入系数的数字为零。 第一个操作数的符号和指数不变。</p></dd></dl>
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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>sqrt</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">sqrt</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the square root of the argument to full precision.</p></dd></dl>
+
<dd><p>将参数的平方根返回到全精度。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>to_eng_string</code><span class="sig-paren">(</span>''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_eng_string</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Convert to a string, using engineering notation if an exponent is needed.</p>
+
<dd><p>如果需要指数,则使用工程符号转换为字符串。</p>
<p>Engineering notation has an exponent which is a multiple of 3. This
+
<p>工程符号的指数是 3 的倍数。 这最多可以在小数位左侧留下 3 位数字,并且可能需要添加一个或两个尾随零。</p>
can leave up to 3 digits to the left of the decimal place and may
+
<p>例如,这将 <code>Decimal('123E+1')</code> 转换为 <code>Decimal('1.23E+3')</code></p></dd></dl>
require the addition of either one or two trailing zeros.</p>
 
<p>For example, this converts <code>Decimal('123E+1')</code> to <code>Decimal('1.23E+3')</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>to_integral</code><span class="sig-paren">(</span>''<span class="n">rounding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_integral</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">rounding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Identical to the [[#decimal.Decimal.to_integral_value|<code>to_integral_value()</code>]] method. The <code>to_integral</code>
+
<dd><p>[[#decimal.Decimal.to_integral_value|to_integral_value()]] 方法相同。 保留 <code>to_integral</code> 名称是为了与旧版本兼容。</p></dd></dl>
name has been kept for compatibility with older versions.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>to_integral_exact</code><span class="sig-paren">(</span>''<span class="n">rounding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_integral_exact</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">rounding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Round to the nearest integer, signaling [[#decimal.Inexact|<code>Inexact</code>]] or
+
<dd><p>舍入到最接近的整数,如果发生舍入,则根据需要发出 [[#decimal.Inexact|不精确]] [[#decimal.Rounded|舍入]] 信号。 如果给定,舍入模式由 <code>rounding</code> 参数确定,否则由给定的 <code>context</code> 确定。 如果没有给出参数,则使用当前上下文的舍入模式。</p></dd></dl>
[[#decimal.Rounded|<code>Rounded</code>]] as appropriate if rounding occurs. The rounding mode is
 
determined by the <code>rounding</code> parameter if given, else by the given
 
<code>context</code>. If neither parameter is given then the rounding mode of the
 
current context is used.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>to_integral_value</code><span class="sig-paren">(</span>''<span class="n">rounding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_integral_value</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">rounding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Round to the nearest integer without signaling [[#decimal.Inexact|<code>Inexact</code>]] or
+
<dd><p>舍入到最接近的整数而不用信号 [[#decimal.Inexact|Inexact]] [[#decimal.Rounded|Rounded]]。 如果给定,则应用 ''rounding''; 否则,在提供的 ''context'' 或当前上下文中使用舍入方法。</p></dd></dl>
[[#decimal.Rounded|<code>Rounded</code>]]. If given, applies ''rounding''; otherwise, uses the
 
rounding method in either the supplied ''context'' or the current context.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
第1,006行: 第760行:
  
 
<span id="logical-operands-label"></span>
 
<span id="logical-operands-label"></span>
=== Logical operands ===
+
=== 逻辑操作数 ===
  
The <code>logical_and()</code>, <code>logical_invert()</code>, <code>logical_or()</code>,
+
<code>logical_and()</code><code>logical_invert()</code><code>logical_or()</code> <code>logical_xor()</code> 方法期望它们的参数是 ''逻辑操作数'' ''逻辑操作数''是一个[[#decimal.Decimal|Decimal]]实例,其指数和符号都为零,并且其数字都是<code>0</code><code>1</code>
and <code>logical_xor()</code> methods expect their arguments to be ''logical
 
operands''. A ''logical operand'' is a [[#decimal.Decimal|<code>Decimal</code>]] instance whose
 
exponent and sign are both zero, and whose digits are all either
 
<code>0</code> or <code>1</code>.
 
  
  
第1,021行: 第771行:
  
 
<span id="decimal-context"></span>
 
<span id="decimal-context"></span>
== 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
+
每个线程都有自己的当前上下文,可以使用 [[#decimal.getcontext|getcontext()]] [[#decimal.setcontext|setcontext()]] 函数访问或更改:
[[#decimal.getcontext|<code>getcontext()</code>]] and [[#decimal.setcontext|<code>setcontext()</code>]] functions:
 
  
; <code>decimal.</code><code>getcontext</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">getcontext</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return the current context for the active thread.
+
: 返回活动线程的当前上下文。
  
; <code>decimal.</code><code>setcontext</code><span class="sig-paren">(</span>''<span class="n">c</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">setcontext</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">c</span></span>''<span class="sig-paren">)</span>
: Set the current context for the active thread to ''c''.
+
: 将活动线程的当前上下文设置为 ''c''
  
You can also use the [[../../reference/compound_stmts#with|<code>with</code>]] statement and the [[#decimal.localcontext|<code>localcontext()</code>]]
+
您还可以使用 [[../../reference/compound_stmts#with|with]] 语句和 [[#decimal.localcontext|localcontext()]] 函数来临时更改活动上下文。
function to temporarily change the active context.
 
  
 
<dl>
 
<dl>
<dt><code>decimal.</code><code>localcontext</code><span class="sig-paren">(</span>''<span class="n">ctx</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">localcontext</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">ctx</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a context manager that will set the current context for the active thread
+
<dd><p>返回一个上下文管理器,它将在进入 with-语句时将活动线程的当前上下文设置为 ''ctx'' 的副本,并在退出 with-语句时恢复先前的上下文。 如果未指定上下文,则使用当前上下文的副本。</p>
to a copy of ''ctx'' on entry to the with-statement and restore the previous context
+
<p>例如,下面的代码将当前的十进制精度设置为 42 位,执行一次计算,然后自动恢复之前的上下文:</p>
when exiting the with-statement. If no context is specified, a copy of the
 
current context is used.</p>
 
<p>For example, the following code sets the current decimal precision to 42 places,
 
performs a calculation, and then automatically restores the previous context:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from decimal import localcontext
+
<syntaxhighlight lang="python3">from decimal import localcontext
  
 
with localcontext() as ctx:
 
with localcontext() as ctx:
 
     ctx.prec = 42  # Perform a high precision calculation
 
     ctx.prec = 42  # Perform a high precision calculation
 
     s = calculate_something()
 
     s = calculate_something()
s = +s  # Round the final result back to the default precision</pre>
+
s = +s  # Round the final result back to the default precision</syntaxhighlight>
  
 
</div>
 
</div>
第1,062行: 第804行:
 
</div></dd></dl>
 
</div></dd></dl>
  
New contexts can also be created using the [[#decimal.Context|<code>Context</code>]] constructor
+
也可以使用下面描述的 [[#decimal.Context|Context]] 构造函数创建新的上下文。 此外,该模块还提供了三个预制上下文:
described below. In addition, the module provides three pre-made contexts:
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>BasicContext</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">BasicContext</span></span></dt>
<dd><p>This is a standard context defined by the General Decimal Arithmetic
+
<dd><p>这是通用十进制算术规范定义的标准上下文。 精度设置为九。 舍入设置为 [[#decimal.ROUND_HALF_UP|ROUND_HALF_UP]]。 清除所有标志。 除了 [[#decimal.Inexact|Inexact]][[#decimal.Rounded|Rounded]] [[#decimal.Subnormal|Subnormal]] 之外,所有陷阱都已启用(视为例外)。</p>
Specification. Precision is set to nine. Rounding is set to
+
<p>由于启用了许多陷阱,因此此上下文可用于调试。</p></dd></dl>
[[#decimal.ROUND_HALF_UP|<code>ROUND_HALF_UP</code>]]. All flags are cleared. All traps are enabled (treated
 
as exceptions) except [[#decimal.Inexact|<code>Inexact</code>]], [[#decimal.Rounded|<code>Rounded</code>]], and
 
[[#decimal.Subnormal|<code>Subnormal</code>]].</p>
 
<p>Because many of the traps are enabled, this context is useful for debugging.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>ExtendedContext</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ExtendedContext</span></span></dt>
<dd><p>This is a standard context defined by the General Decimal Arithmetic
+
<dd><p>这是通用十进制算术规范定义的标准上下文。 精度设置为九。 舍入设置为 [[#decimal.ROUND_HALF_EVEN|ROUND_HALF_EVEN]]。 清除所有标志。 没有启用陷阱(因此在计算过程中不会引发异常)。</p>
Specification. Precision is set to nine. Rounding is set to
+
<p>由于陷阱被禁用,此上下文对于更喜欢具有 <code>NaN</code> <code>Infinity</code> 结果值而不是引发异常的应用程序很有用。 这允许应用程序在存在可能停止程序的情况下完成运行。</p></dd></dl>
[[#decimal.ROUND_HALF_EVEN|<code>ROUND_HALF_EVEN</code>]]. All flags are cleared. No traps are enabled (so that
 
exceptions are not raised during computations).</p>
 
<p>Because the traps are disabled, this context is useful for applications that
 
prefer to have result value of <code>NaN</code> or <code>Infinity</code> instead of
 
raising exceptions. This allows an application to complete a run in the
 
presence of conditions that would otherwise halt the program.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>DefaultContext</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">DefaultContext</span></span></dt>
<dd><p>This context is used by the [[#decimal.Context|<code>Context</code>]] constructor as a prototype for new
+
<dd><p>[[#decimal.Context|Context]] 构造函数使用此上下文作为新上下文的原型。 更改字段(如精度)会更改由 [[#decimal.Context|Context]] 构造函数创建的新上下文的默认值。</p>
contexts. Changing a field (such a precision) has the effect of changing the
+
<p>此上下文在多线程环境中最有用。 在线程启动之前更改字段之一具有设置系统范围默认值的效果。 不建议在线程启动后更改字段,因为它需要线程同步以防止竞争条件。</p>
default for new contexts created by the [[#decimal.Context|<code>Context</code>]] constructor.</p>
+
<p>在单线程环境中,最好根本不使用此上下文。 相反,只需如下所述显式地创建上下文。</p>
<p>This context is most useful in multi-threaded environments. Changing one of the
+
<p>默认值为 <code>prec</code>=<code>28</code><code>rounding</code>=[[#decimal.ROUND_HALF_EVEN|ROUND_HALF_EVEN]],并为 [[#decimal.Overflow|Overflow]]、InvalidOperation 启用陷阱X141X] [[#decimal.DivisionByZero|DivisionByZero]]</p></dd></dl>
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.</p>
 
<p>In single threaded environments, it is preferable to not use this context at
 
all. Instead, simply create contexts explicitly as described below.</p>
 
<p>The default values are <code>prec</code>=<code>28</code>,
 
<code>rounding</code>=[[#decimal.ROUND_HALF_EVEN|<code>ROUND_HALF_EVEN</code>]],
 
and enabled traps for [[#decimal.Overflow|<code>Overflow</code>]], [[#decimal.InvalidOperation|<code>InvalidOperation</code>]], and
 
[[#decimal.DivisionByZero|<code>DivisionByZero</code>]].</p></dd></dl>
 
  
In addition to the three supplied contexts, new contexts can be created with the
+
除了提供的三个上下文之外,还可以使用 [[#decimal.Context|Context]] 构造函数创建新的上下文。
[[#decimal.Context|<code>Context</code>]] constructor.
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Context</code><span class="sig-paren">(</span>''<span class="n">prec</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">rounding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">Emin</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">Emax</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">capitals</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">clamp</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">flags</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">traps</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Context</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">prec</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">rounding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">Emin</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">Emax</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">capitals</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">clamp</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">flags</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">traps</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Creates a new context. If a field is not specified or is [[../constants#None|<code>None</code>]], the
+
<dd><p>创建一个新的上下文。 如果字段未指定或为 [[../constants#None|None]],则从 [[#decimal.DefaultContext|DefaultContext]] 复制默认值。 如果 ''flags'' 字段未指定或为 [[../constants#None|None]],则清除所有标志。</p>
default values are copied from the [[#decimal.DefaultContext|<code>DefaultContext</code>]]. If the ''flags''
+
<p>''prec'' [<code>1</code>, [[#decimal.MAX_PREC|MAX_PREC]]] 范围内的整数,用于设置上下文中算术运算的精度。</p>
field is not specified or is [[../constants#None|<code>None</code>]], all flags are cleared.</p>
+
<p>''rounding'' 选项是 [[#rounding-modes|Rounding Modes]] 部分中列出的常量之一。</p>
<p>''prec'' is an integer in the range [<code>1</code>, [[#decimal.MAX_PREC|<code>MAX_PREC</code>]]] that sets
+
<p>''traps'' ''flags'' 字段列出了要设置的任何信号。 通常,新上下文应该只设置陷阱并清除标志。</p>
the precision for arithmetic operations in the context.</p>
+
<p>''Emin'' ''Emax'' 字段是指定指数允许的外部限制的整数。 ''Emin'' 必须在 [<nowiki/>[[#decimal.MIN_EMIN|MIN_EMIN]]<code>0</code>]''Emax'' 范围内 [<code>0</code>[[#decimal.MAX_EMAX|范围内MAX_EMAX]]]</p>
<p>The ''rounding'' option is one of the constants listed in the section
+
<p>''capitals'' 字段是 <code>0</code> <code>1</code>(默认值)。 如果设置为 <code>1</code>,指数以大写 <code>E</code> 打印; 否则,使用小写 <code>e</code><code>Decimal('6.02e+23')</code></p>
[[#rounding-modes|Rounding Modes]].</p>
+
<p>''clamp'' 字段是 <code>0</code>(默认值)或 <code>1</code>。 如果设置为 <code>1</code>,则在此上下文中可表示的 [[#decimal.Decimal|Decimal]] 实例的指数 <code>e</code> 严格限制在 <code>Emin - prec + 1 &lt;= e &lt;= Emax - prec + 1</code> 范围内。 如果 ''clamp'' <code>0</code>,那么一个较弱的条件成立:[[#decimal.Decimal|Decimal]] 实例的调整指数至多是 <code>Emax</code>。 当 ''clamp'' <code>1</code> 时,一个大的正常数将尽可能减少其指数并在其系数中添加相应数量的零,以适应指数约束; 这会保留数字的值,但会丢失有关重要尾随零的信息。 例如:</p>
<p>The ''traps'' and ''flags'' fields list any signals to be set. Generally, new
 
contexts should only set traps and leave the flags clear.</p>
 
<p>The ''Emin'' and ''Emax'' fields are integers specifying the outer limits allowable
 
for exponents. ''Emin'' must be in the range [<nowiki/>[[#decimal.MIN_EMIN|<code>MIN_EMIN</code>]], <code>0</code>],
 
''Emax'' in the range [<code>0</code>, [[#decimal.MAX_EMAX|<code>MAX_EMAX</code>]]].</p>
 
<p>The ''capitals'' field is either <code>0</code> or <code>1</code> (the default). If set to
 
<code>1</code>, exponents are printed with a capital <code>E</code>; otherwise, a
 
lowercase <code>e</code> is used: <code>Decimal('6.02e+23')</code>.</p>
 
<p>The ''clamp'' field is either <code>0</code> (the default) or <code>1</code>.
 
If set to <code>1</code>, the exponent <code>e</code> of a [[#decimal.Decimal|<code>Decimal</code>]]
 
instance representable in this context is strictly limited to the
 
range <code>Emin - prec + 1 &lt;= e &lt;= Emax - prec + 1</code>. If ''clamp'' is
 
<code>0</code> then a weaker condition holds: the adjusted exponent of
 
the [[#decimal.Decimal|<code>Decimal</code>]] instance is at most <code>Emax</code>. When ''clamp'' is
 
<code>1</code>, 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. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
+
<syntaxhighlight lang="python3">>>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
Decimal('1.23000E+999')</pre>
+
Decimal('1.23000E+999')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>A ''clamp'' value of <code>1</code> allows compatibility with the
+
<p><code>1</code> 的 ''clamp'' 值允许与 IEEE 754 中指定的固定宽度十进制交换格式兼容。</p>
fixed-width decimal interchange formats specified in IEEE 754.</p>
+
<p>[[#decimal.Context|Context]] 类定义了几个通用方法以及大量直接在给定上下文中进行算术的方法。 此外,对于上述每个 [[#decimal.Decimal|Decimal]] 方法(<code>adjusted()</code> <code>as_tuple()</code> 方法除外),都有一个对应的 [[#decimal.Context|Context]] 方法. 例如,对于 [[#decimal.Context|Context]] 实例 <code>C</code> [[#decimal.Decimal|Decimal]] 实例 <code>x</code><code>C.exp(x)</code> 等价于 <code>x.exp(context=C)</code> . 每个 [[#decimal.Context|Context]] 方法都接受一个 Python 整数([[../functions#int|int]] 的一个实例),只要接受 Decimal 实例。</p>
<p>The [[#decimal.Context|<code>Context</code>]] class defines several general purpose methods as well as
 
a large number of methods for doing arithmetic directly in a given context.
 
In addition, for each of the [[#decimal.Decimal|<code>Decimal</code>]] methods described above (with
 
the exception of the <code>adjusted()</code> and <code>as_tuple()</code> methods) there is
 
a corresponding [[#decimal.Context|<code>Context</code>]] method. For example, for a [[#decimal.Context|<code>Context</code>]]
 
instance <code>C</code> and [[#decimal.Decimal|<code>Decimal</code>]] instance <code>x</code>, <code>C.exp(x)</code> is
 
equivalent to <code>x.exp(context=C)</code>. Each [[#decimal.Context|<code>Context</code>]] method accepts a
 
Python integer (an instance of [[../functions#int|<code>int</code>]]) anywhere that a
 
Decimal instance is accepted.</p>
 
 
<dl>
 
<dl>
<dt><code>clear_flags</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">clear_flags</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Resets all of the flags to <code>0</code>.</p></dd></dl>
+
<dd><p>将所有标志重置为 <code>0</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>clear_traps</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">clear_traps</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Resets all of the traps to <code>0</code>.</p>
+
<dd><p>将所有陷阱重置为 <code>0</code></p>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.3 新版功能.</span></p>
+
<p><span class="versionmodified added">3.3 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return a duplicate of the context.</p></dd></dl>
+
<dd><p>返回上下文的副本。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>copy_decimal</code><span class="sig-paren">(</span>''<span class="n">num</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_decimal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">num</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a copy of the Decimal instance num.</p></dd></dl>
+
<dd><p>返回 Decimal 实例 num 的副本。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>create_decimal</code><span class="sig-paren">(</span>''<span class="n">num</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">create_decimal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">num</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Creates a new Decimal instance from ''num'' but using ''self'' as
+
<dd><p>''num'' 创建一个新的 Decimal 实例,但使用 ''self'' 作为上下文。 与 [[#decimal.Decimal|Decimal]] 构造函数不同,上下文精度、舍入方法、标志和陷阱应用于转换。</p>
context. Unlike the [[#decimal.Decimal|<code>Decimal</code>]] constructor, the context precision,
+
<p>这很有用,因为常量的精度通常高于应用程序所需的精度。 另一个好处是四舍五入可以立即消除超出当前精度的数字的意外影响。 在以下示例中,使用未舍入的输入意味着将零添加到总和可以更改结果:</p>
rounding method, flags, and traps are applied to the conversion.</p>
 
<p>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:</p>
 
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 3
+
<pre class="pycon3">&gt;&gt;&gt; getcontext().prec = 3
 
&gt;&gt;&gt; Decimal('3.4445') + Decimal('1.0023')
 
&gt;&gt;&gt; Decimal('3.4445') + Decimal('1.0023')
 
Decimal('4.45')
 
Decimal('4.45')
第1,197行: 第884行:
  
 
</div>
 
</div>
<p>This method implements the to-number operation of the IBM specification.
+
<p>该方法实现了IBM 规范的to-number 操作。 如果参数是字符串,则不允许前导或尾随空格或下划线。</p></dd></dl>
If the argument is a string, no leading or trailing whitespace or
 
underscores are permitted.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>create_decimal_from_float</code><span class="sig-paren">(</span>''<span class="n">f</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">create_decimal_from_float</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">f</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Creates a new Decimal instance from a float ''f'' but rounding using ''self''
+
<dd><p>从浮点数 ''f'' 创建一个新的 Decimal 实例,但使用 ''self'' 作为上下文进行舍入。 与 [[#decimal.Decimal.from_float|Decimal.from_float()]] 类方法不同,上下文精度、舍入方法、标志和陷阱应用于转换。</p>
as the context. Unlike the [[#decimal.Decimal.from_float|<code>Decimal.from_float()</code>]] class method,
 
the context precision, rounding method, flags, and traps are applied to
 
the conversion.</p>
 
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; context = Context(prec=5, rounding=ROUND_DOWN)
+
<pre class="pycon3">&gt;&gt;&gt; context = Context(prec=5, rounding=ROUND_DOWN)
 
&gt;&gt;&gt; context.create_decimal_from_float(math.pi)
 
&gt;&gt;&gt; context.create_decimal_from_float(math.pi)
 
Decimal('3.1415')
 
Decimal('3.1415')
第1,225行: 第907行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.1 新版功能.</span></p>
+
<p><span class="versionmodified added">3.1 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>Etiny</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">Etiny</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a value equal to <code>Emin - prec + 1</code> which is the minimum exponent
+
<dd><p>返回一个等于 <code>Emin - prec + 1</code> 的值,这是次正规结果的最小指数值。 发生下溢时,指数设置为 [[#decimal.Context.Etiny|Etiny]]</p></dd></dl>
value for subnormal results. When underflow occurs, the exponent is set
 
to [[#decimal.Context.Etiny|<code>Etiny</code>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>Etop</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">Etop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a value equal to <code>Emax - prec + 1</code>.</p></dd></dl>
+
<dd><p>返回一个等于 <code>Emax - prec + 1</code> 的值。</p></dd></dl>
  
<p>The usual approach to working with decimals is to create [[#decimal.Decimal|<code>Decimal</code>]]
+
<p>处理小数的常用方法是创建 [[#decimal.Decimal|Decimal]] 实例,然后应用在活动线程的当前上下文中发生的算术运算。 另一种方法是使用上下文方法在特定上下文中进行计算。 这些方法类似于 [[#decimal.Decimal|Decimal]] 类的方法,这里只简要介绍。</p>
instances and then apply arithmetic operations which take place within the
 
current context for the active thread. An alternative approach is to use
 
context methods for calculating within a specific context. The methods are
 
similar to those for the [[#decimal.Decimal|<code>Decimal</code>]] class and are only briefly
 
recounted here.</p>
 
 
<dl>
 
<dl>
<dt><code>abs</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">abs</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the absolute value of ''x''.</p></dd></dl>
+
<dd><p>返回 ''x'' 的绝对值。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>add</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">add</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the sum of ''x'' and ''y''.</p></dd></dl>
+
<dd><p>返回 ''x'' ''y'' 的和。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>canonical</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">canonical</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the same Decimal object ''x''.</p></dd></dl>
+
<dd><p>返回相同的 Decimal 对象 ''x''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>compare</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares ''x'' and ''y'' numerically.</p></dd></dl>
+
<dd><p>在数值上比较 ''x'' ''y''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>compare_signal</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare_signal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares the values of the two operands numerically.</p></dd></dl>
+
<dd><p>以数字方式比较两个操作数的值。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>compare_total</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare_total</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares two operands using their abstract representation.</p></dd></dl>
+
<dd><p>使用抽象表示比较两个操作数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>compare_total_mag</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compare_total_mag</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares two operands using their abstract representation, ignoring sign.</p></dd></dl>
+
<dd><p>使用抽象表示比较两个操作数,忽略符号。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>copy_abs</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_abs</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a copy of ''x'' with the sign set to 0.</p></dd></dl>
+
<dd><p>返回符号设置为 0 的 ''x'' 的副本。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>copy_negate</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_negate</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a copy of ''x'' with the sign inverted.</p></dd></dl>
+
<dd><p>返回符号反转的 ''x'' 的副本。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>copy_sign</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy_sign</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Copies the sign from ''y'' to ''x''.</p></dd></dl>
+
<dd><p>将符号从 ''y'' 复制到 ''x''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>divide</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">divide</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return ''x'' divided by ''y''.</p></dd></dl>
+
<dd><p>返回 ''x'' 除以 ''y''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>divide_int</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">divide_int</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return ''x'' divided by ''y'', truncated to an integer.</p></dd></dl>
+
<dd><p>返回 ''x'' 除以 ''y'',截断为整数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>divmod</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">divmod</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Divides two numbers and returns the integer part of the result.</p></dd></dl>
+
<dd><p>将两个数字相除并返回结果的整数部分。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>exp</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">exp</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns e ** x.</p></dd></dl>
+
<dd><p>返回 e ** x。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>fma</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>'', ''<span class="n">z</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">fma</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>'', ''<span class="n"><span class="pre">z</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns ''x'' multiplied by ''y'', plus ''z''.</p></dd></dl>
+
<dd><p>返回 ''x'' 乘以 ''y'',再加上 ''z''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_canonical</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_canonical</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is canonical; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是规范的,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_finite</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_finite</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is finite; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是有限的,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_infinite</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_infinite</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is infinite; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是无限的,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_nan</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_nan</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is a qNaN or sNaN; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是 qNaN 或 sNaN,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_normal</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_normal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is a normal number; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是正常数,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_qnan</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_qnan</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is a quiet NaN; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是一个安静的 NaN,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_signed</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_signed</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is negative; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 为负,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_snan</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_snan</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is a signaling NaN; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 是信号 NaN,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_subnormal</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_subnormal</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is subnormal; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 低于正常值,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>is_zero</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">is_zero</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if ''x'' is a zero; otherwise returns <code>False</code>.</p></dd></dl>
+
<dd><p>如果 ''x'' 为零,则返回 <code>True</code>; 否则返回 <code>False</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>ln</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">ln</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the natural (base e) logarithm of ''x''.</p></dd></dl>
+
<dd><p>返回 ''x'' 的自然(以 e 为底)对数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>log10</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">log10</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the base 10 logarithm of ''x''.</p></dd></dl>
+
<dd><p>返回 ''x'' 的以 10 为底的对数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>logb</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logb</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the exponent of the magnitude of the operand's MSD.</p></dd></dl>
+
<dd><p>返回操作数的 MSD 大小的指数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>logical_and</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_and</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Applies the logical operation ''and'' between each operand's digits.</p></dd></dl>
+
<dd><p>在每个操作数的数字之间应用逻辑运算 '''' </p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>logical_invert</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_invert</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Invert all the digits in ''x''.</p></dd></dl>
+
<dd><p>反转 ''x'' 中的所有数字。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>logical_or</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_or</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Applies the logical operation ''or'' between each operand's digits.</p></dd></dl>
+
<dd><p>在每个操作数的数字之间应用逻辑运算 '''' </p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>logical_xor</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">logical_xor</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Applies the logical operation ''xor'' between each operand's digits.</p></dd></dl>
+
<dd><p>在每个操作数的数字之间应用逻辑运算 ''xor''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>max</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">max</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares two values numerically and returns the maximum.</p></dd></dl>
+
<dd><p>以数字方式比较两个值并返回最大值。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>max_mag</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">max_mag</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares the values numerically with their sign ignored.</p></dd></dl>
+
<dd><p>以数字方式比较值,忽略其符号。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>min</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">min</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares two values numerically and returns the minimum.</p></dd></dl>
+
<dd><p>以数字方式比较两个值并返回最小值。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>min_mag</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">min_mag</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compares the values numerically with their sign ignored.</p></dd></dl>
+
<dd><p>以数字方式比较值,忽略其符号。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>minus</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">minus</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Minus corresponds to the unary prefix minus operator in Python.</p></dd></dl>
+
<dd><p>减号对应于 Python 中的一元前缀减号运算符。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>multiply</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">multiply</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the product of ''x'' and ''y''.</p></dd></dl>
+
<dd><p>返回 ''x'' ''y'' 的乘积。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>next_minus</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">next_minus</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the largest representable number smaller than ''x''.</p></dd></dl>
+
<dd><p>返回小于 ''x'' 的最大可表示数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>next_plus</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">next_plus</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the smallest representable number larger than ''x''.</p></dd></dl>
+
<dd><p>返回大于 ''x'' 的最小可表示数字。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>next_toward</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">next_toward</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the number closest to ''x'', in direction towards ''y''.</p></dd></dl>
+
<dd><p>返回最接近 ''x'' 的数字,方向为 ''y''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>normalize</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">normalize</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Reduces ''x'' to its simplest form.</p></dd></dl>
+
<dd><p>''x'' 简化为最简单的形式。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>number_class</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">number_class</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns an indication of the class of ''x''.</p></dd></dl>
+
<dd><p>返回 ''x'' 类的指示。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>plus</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">plus</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Plus corresponds to the unary prefix plus operator in Python. This
+
<dd><p>加号对应于 Python 中的一元前缀加号运算符。 此操作应用上下文精度和舍入,因此它是 ''不是'' 身份操作。</p></dd></dl>
operation applies the context precision and rounding, so it is ''not'' an
 
identity operation.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>power</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>'', ''<span class="n">modulo</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">power</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>'', ''<span class="n"><span class="pre">modulo</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return <code>x</code> to the power of <code>y</code>, reduced modulo <code>modulo</code> if given.</p>
+
<dd><p><code>x</code> 返回到 <code>y</code> 的幂,如果给定,则减少模 <code>modulo</code></p>
<p>With two arguments, compute <code>x**y</code>. If <code>x</code> is negative then <code>y</code>
+
<p>使用两个参数,计算 <code>x**y</code>。 如果 <code>x</code> 为负,则 <code>y</code> 必须是整数。 结果将是不精确的,除非 <code>y</code> 是整数并且结果是有限的并且可以精确地用“精度”数字表示。 使用上下文的舍入模式。 结果在 Python 版本中总是正确四舍五入。</p>
must be integral. The result will be inexact unless <code>y</code> is integral and
+
<p><code>Decimal(0) ** Decimal(0)</code> 导致 <code>InvalidOperation</code>,如果 <code>InvalidOperation</code> 未被捕获,则导致 <code>Decimal('NaN')</code></p>
the result is finite and can be expressed exactly in 'precision' digits.
 
The rounding mode of the context is used. Results are always correctly-rounded
 
in the Python version.</p>
 
<p><code>Decimal(0) ** Decimal(0)</code> results in <code>InvalidOperation</code>, and if <code>InvalidOperation</code>
 
is not trapped, then results in <code>Decimal('NaN')</code>.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>The C module computes [[#decimal.Context.power|<code>power()</code>]] in terms of the correctly-rounded
+
<p><span class="versionmodified changed">3.3 版更改:</span>C 模块根据正确舍入的 [[#decimal.Context.exp|exp()]] [[#decimal.Context.ln|ln()]] 计算 [[#decimal.Context.power|power()]]职能。 结果是明确定义的,但只是“几乎总是正确四舍五入”。</p>
[[#decimal.Context.exp|<code>exp()</code>]] and [[#decimal.Context.ln|<code>ln()</code>]] functions. The result is well-defined but
 
only &quot;almost always correctly-rounded&quot;.</p>
 
  
 
</div>
 
</div>
<p>With three arguments, compute <code>(x**y) % modulo</code>. For the three argument
+
<p>使用三个参数,计算 <code>(x**y) % modulo</code>。 对于三参数形式,对参数的以下限制成立:</p>
form, the following restrictions on the arguments hold:</p>
 
 
<blockquote><div>
 
<blockquote><div>
  
 
<ul>
 
<ul>
<li><p>all three arguments must be integral</p></li>
+
<li><p>所有三个参数都必须是整数</p></li>
<li><p><code>y</code> must be nonnegative</p></li>
+
<li><p><code>y</code> 必须为非负</p></li>
<li><p>at least one of <code>x</code> or <code>y</code> must be nonzero</p></li>
+
<li><p><code>x</code> <code>y</code> 中的至少一个必须是非零值</p></li>
<li><p><code>modulo</code> must be nonzero and have at most 'precision' digits</p></li></ul>
+
<li><p><code>modulo</code> 必须为非零且最多为“精度”数字</p></li></ul>
  
  
 
</div></blockquote>
 
</div></blockquote>
<p>The value resulting from <code>Context.power(x, y, modulo)</code> is
+
<p><code>Context.power(x, y, modulo)</code> 产生的值等于通过以无限精度计算 <code>(x**y) % modulo</code> 获得的值,但计算效率更高。 结果的指数为零,与 <code>x</code><code>y</code> <code>modulo</code> 的指数无关。 结果总是准确的。</p></dd></dl>
equal to the value that would be obtained by computing <code>(x**y) % modulo</code> with unbounded precision, but is computed more
 
efficiently. The exponent of the result is zero, regardless of
 
the exponents of <code>x</code>, <code>y</code> and <code>modulo</code>. The result is
 
always exact.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>quantize</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">quantize</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a value equal to ''x'' (rounded), having the exponent of ''y''.</p></dd></dl>
+
<dd><p>返回一个等于 ''x''(四舍五入)的值,其指数为 ''y''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>radix</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">radix</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Just returns 10, as this is Decimal, :)</p></dd></dl>
+
<dd><p>只返回 10,因为这是十进制,:)</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>remainder</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">remainder</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the remainder from integer division.</p>
+
<dd><p>返回整数除法的余数。</p>
<p>The sign of the result, if non-zero, is the same as that of the original
+
<p>结果的符号(如果非零)与原始被除数的符号相同。</p></dd></dl>
dividend.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>remainder_near</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">remainder_near</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>x - y * n</code>, where ''n'' is the integer nearest the exact value
+
<dd><p>返回 <code>x - y * n</code>,其中 ''n'' 是最接近 <code>x / y</code> 精确值的整数(如果结果为 0,则其符号将是 ''x'' 的符号])。</p></dd></dl>
of <code>x / y</code> (if the result is 0 then its sign will be the sign of ''x'').</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>rotate</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">rotate</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a rotated copy of ''x'', ''y'' times.</p></dd></dl>
+
<dd><p>返回 ''x''''y'' 次的旋转副本。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>same_quantum</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">same_quantum</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns <code>True</code> if the two operands have the same exponent.</p></dd></dl>
+
<dd><p>如果两个操作数具有相同的指数,则返回 <code>True</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>scaleb</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">scaleb</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the first operand after adding the second value its exp.</p></dd></dl>
+
<dd><p>将第二个值与 exp 相加后返回第一个操作数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>shift</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">shift</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a shifted copy of ''x'', ''y'' times.</p></dd></dl>
+
<dd><p>返回 ''x''''y'' 次的移位副本。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>sqrt</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">sqrt</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Square root of a non-negative number to context precision.</p></dd></dl>
+
<dd><p>非负数的平方根到上下文精度。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>subtract</code><span class="sig-paren">(</span>''<span class="n">x</span>'', ''<span class="n">y</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">subtract</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>'', ''<span class="n"><span class="pre">y</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the difference between ''x'' and ''y''.</p></dd></dl>
+
<dd><p>返回 ''x'' ''y'' 之间的差值。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>to_eng_string</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_eng_string</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Convert to a string, using engineering notation if an exponent is needed.</p>
+
<dd><p>如果需要指数,则使用工程符号转换为字符串。</p>
<p>Engineering notation has an exponent which is a multiple of 3. This
+
<p>工程符号的指数是 3 的倍数。 这最多可以在小数位左侧留下 3 位数字,并且可能需要添加一个或两个尾随零。</p></dd></dl>
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.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>to_integral_exact</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_integral_exact</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Rounds to an integer.</p></dd></dl>
+
<dd><p>舍入为整数。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>to_sci_string</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">to_sci_string</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Converts a number to a string using scientific notation.</p></dd></dl>
+
<dd><p>使用科学记数法将数字转换为字符串。</p></dd></dl>
 
</dd></dl>
 
</dd></dl>
  
第1,522行: 第1,179行:
  
 
<span id="decimal-rounding-modes"></span>
 
<span id="decimal-rounding-modes"></span>
== Constants ==
+
== 常数 ==
  
The constants in this section are only relevant for the C module. They
+
本节中的常量仅与 C 模块相关。 为了兼容性,它们也包含在纯 Python 版本中。
are also included in the pure Python version for compatibility.
 
  
 
{|
 
{|
 
!width="28%"|
 
!width="28%"|
!width="28%"| 32-bit
+
!width="28%"| 32
!width="42%"| 64-bit
+
!width="42%"| 64
 
|-
 
|-
 
|
 
|
; <code>decimal.</code><code>MAX_PREC</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">MAX_PREC</span></span>
 
:
 
:
 
| <code>425000000</code>
 
| <code>425000000</code>
第1,539行: 第1,195行:
 
|-
 
|-
 
|
 
|
; <code>decimal.</code><code>MAX_EMAX</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">MAX_EMAX</span></span>
 
:
 
:
 
| <code>425000000</code>
 
| <code>425000000</code>
第1,545行: 第1,201行:
 
|-
 
|-
 
|
 
|
; <code>decimal.</code><code>MIN_EMIN</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">MIN_EMIN</span></span>
 
:
 
:
 
| <code>-425000000</code>
 
| <code>-425000000</code>
第1,551行: 第1,207行:
 
|-
 
|-
 
|
 
|
; <code>decimal.</code><code>MIN_ETINY</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">MIN_ETINY</span></span>
 
:
 
:
 
| <code>-849999999</code>
 
| <code>-849999999</code>
第1,557行: 第1,213行:
 
|}
 
|}
  
; <code>decimal.</code><code>HAVE_THREADS</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">HAVE_THREADS</span></span>
: The value is <code>True</code>. Deprecated, because Python now always has threads.
+
: 值为 <code>True</code>。 已弃用,因为 Python 现在总是有线程。
  
 
<div class="deprecated">
 
<div class="deprecated">
  
<span class="versionmodified deprecated">3.9 版后已移除.</span>
+
<span class="versionmodified deprecated">3.9 版起已弃用。</span>
  
  
 
</div>
 
</div>
; <code>decimal.</code><code>HAVE_CONTEXTVAR</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">HAVE_CONTEXTVAR</span></span>
: The default value is <code>True</code>. If Python is compiled <code>--without-decimal-contextvar</code>, the C version uses a thread-local rather than a coroutine-local context and the value is <code>False</code>. This is slightly faster in some nested context scenarios.
+
: 默认值为 <code>True</code>。 如果 Python 编译为 <code>--without-decimal-contextvar</code>,则 C 版本使用线程本地而不是协程本地上下文,值为 <code>False</code>。 在某些嵌套上下文场景中,这会稍微快一些。
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.9 新版功能: </span>backported to 3.7 and 3.8.
+
<span class="versionmodified added"> 3.9 版新功能:</span> 向后移植到 3.7 3.8。
  
  
第1,579行: 第1,235行:
 
<div id="rounding-modes" class="section">
 
<div id="rounding-modes" class="section">
  
== Rounding modes ==
+
== 舍入模式 ==
  
; <code>decimal.</code><code>ROUND_CEILING</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_CEILING</span></span>
: Round towards <code>Infinity</code>.
+
: <code>Infinity</code> 舍入。
  
; <code>decimal.</code><code>ROUND_DOWN</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_DOWN</span></span>
: Round towards zero.
+
: 向零舍入。
  
; <code>decimal.</code><code>ROUND_FLOOR</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_FLOOR</span></span>
: Round towards <code>-Infinity</code>.
+
: <code>-Infinity</code> 舍入。
  
; <code>decimal.</code><code>ROUND_HALF_DOWN</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_HALF_DOWN</span></span>
: Round to nearest with ties going towards zero.
+
: 舍入到最接近的关系,并趋向于零。
  
; <code>decimal.</code><code>ROUND_HALF_EVEN</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_HALF_EVEN</span></span>
: Round to nearest with ties going to nearest even integer.
+
: 舍入到最接近的关系到最接近的偶数整数。
  
; <code>decimal.</code><code>ROUND_HALF_UP</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_HALF_UP</span></span>
: Round to nearest with ties going away from zero.
+
: 舍入到最接近的关系,从零开始。
  
; <code>decimal.</code><code>ROUND_UP</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_UP</span></span>
: Round away from zero.
+
: 从零舍入。
  
; <code>decimal.</code><code>ROUND_05UP</code>
+
; <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">ROUND_05UP</span></span>
: Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero.
+
: 如果向零舍入后的最后一位数字是 0 或 5,则从零舍入; 否则向零舍入。
  
  
第1,610行: 第1,266行:
  
 
<span id="decimal-signals"></span>
 
<span id="decimal-signals"></span>
== 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 异常。 例如,如果设置了 [[#decimal.DivisionByZero|DivisionByZero]] 陷阱,则在遇到该条件时会引发 [[#decimal.DivisionByZero|DivisionByZero]] 异常。
Python exception to be raised. For example, if the [[#decimal.DivisionByZero|<code>DivisionByZero</code>]] trap
 
is set, then a [[#decimal.DivisionByZero|<code>DivisionByZero</code>]] exception is raised upon encountering the
 
condition.
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Clamped</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Clamped</span></span></dt>
<dd><p>Altered an exponent to fit representation constraints.</p>
+
<dd><p>更改了指数以适应表示约束。</p>
<p>Typically, clamping occurs when an exponent falls outside the context's
+
<p>通常,当指数超出上下文的 <code>Emin</code> <code>Emax</code> 限制时,就会发生钳位。 如果可能,通过向系数添加零来减小指数以适合。</p></dd></dl>
<code>Emin</code> and <code>Emax</code> limits. If possible, the exponent is reduced to
 
fit by adding zeros to the coefficient.</p></dd></dl>
 
  
; ''class'' <code>decimal.</code><code>DecimalException</code>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">DecimalException</span></span>
: Base class for other signals and a subclass of [[../exceptions#ArithmeticError|<code>ArithmeticError</code>]].
+
: 其他信号的基类和 [[../exceptions#ArithmeticError|ArithmeticError]] 的子类。
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>DivisionByZero</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">DivisionByZero</span></span></dt>
<dd><p>Signals the division of a non-infinite number by zero.</p>
+
<dd><p>表示非无限数除以零。</p>
<p>Can occur with division, modulo division, or when raising a number to a negative
+
<p>可以与除法、模除法一起发生,或者在将一个数字提高到负幂时发生。 如果该信号未被捕获,则返回 <code>Infinity</code> <code>-Infinity</code>,其符号由计算输入确定。</p></dd></dl>
power. If this signal is not trapped, returns <code>Infinity</code> or
 
<code>-Infinity</code> with the sign determined by the inputs to the calculation.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Inexact</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Inexact</span></span></dt>
<dd><p>Indicates that rounding occurred and the result is not exact.</p>
+
<dd><p>表示发生了舍入并且结果不准确。</p>
<p>Signals when non-zero digits were discarded during rounding. The rounded result
+
<p>在舍入期间丢弃非零数字时的信号。 返回四舍五入的结果。 信号标志或陷阱用于检测结果何时不准确。</p></dd></dl>
is returned. The signal flag or trap is used to detect when results are
 
inexact.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>InvalidOperation</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">InvalidOperation</span></span></dt>
<dd><p>An invalid operation was performed.</p>
+
<dd><p>执行了无效的操作。</p>
<p>Indicates that an operation was requested that does not make sense. If not
+
<p>表示请求的操作没有意义。 如果没有被捕获,则返回 <code>NaN</code>。 可能的原因包括:</p>
trapped, returns <code>NaN</code>. Possible causes include:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Infinity - Infinity
+
<syntaxhighlight lang="python3">Infinity - Infinity
 
0 * Infinity
 
0 * Infinity
 
Infinity / Infinity
 
Infinity / Infinity
 
x % 0
 
x % 0
 
Infinity % x
 
Infinity % x
sqrt(-x) and x &gt; 0
+
sqrt(-x) and x > 0
 
0 ** 0
 
0 ** 0
 
x ** (non-integer)
 
x ** (non-integer)
x ** Infinity</pre>
+
x ** Infinity</syntaxhighlight>
  
 
</div>
 
</div>
第1,673行: 第1,315行:
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Overflow</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Overflow</span></span></dt>
<dd><p>Numerical overflow.</p>
+
<dd><p>数值溢出。</p>
<p>Indicates the exponent is larger than <code>Emax</code> after rounding has
+
<p>表示在发生舍入后指数大于 <code>Emax</code>。 如果没有被困,结果取决于舍入模式,要么向内拉到最大的可表示有限数,要么向外舍入到 <code>Infinity</code>。 在任何一种情况下,[[#decimal.Inexact|Inexact]] [[#decimal.Rounded|Rounded]] 也会发出信号。</p></dd></dl>
occurred. If not trapped, the result depends on the rounding mode, either
 
pulling inward to the largest representable finite number or rounding outward
 
to <code>Infinity</code>. In either case, [[#decimal.Inexact|<code>Inexact</code>]] and [[#decimal.Rounded|<code>Rounded</code>]]
 
are also signaled.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Rounded</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Rounded</span></span></dt>
<dd><p>Rounding occurred though possibly no information was lost.</p>
+
<dd><p>尽管可能没有信息丢失,但发生了舍入。</p>
<p>Signaled whenever rounding discards digits; even if those digits are zero
+
<p>每当舍入丢弃数字时发出信号; 即使这些数字为零(例如将 <code>5.00</code> 舍入为 <code>5.0</code>)。 如果没有被捕获,则返回结果不变。 该信号用于检测有效数字的丢失。</p></dd></dl>
(such as rounding <code>5.00</code> to <code>5.0</code>). If not trapped, returns
 
the result unchanged. This signal is used to detect loss of significant
 
digits.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Subnormal</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Subnormal</span></span></dt>
<dd><p>Exponent was lower than <code>Emin</code> prior to rounding.</p>
+
<dd><p>在四舍五入之前,指数低于 <code>Emin</code></p>
<p>Occurs when an operation result is subnormal (the exponent is too small). If
+
<p>当运算结果不正常(指数太小)时发生。 如果没有被捕获,则返回结果不变。</p></dd></dl>
not trapped, returns the result unchanged.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>Underflow</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">Underflow</span></span></dt>
<dd><p>Numerical underflow with result rounded to zero.</p>
+
<dd><p>数值下溢,结果四舍五入为零。</p>
<p>Occurs when a subnormal result is pushed to zero by rounding. [[#decimal.Inexact|<code>Inexact</code>]]
+
<p>在通过四舍五入将次正规结果推到零时发生。 [[#decimal.Inexact|不精确]] [[#decimal.Subnormal|次正常]] 也会发出信号。</p></dd></dl>
and [[#decimal.Subnormal|<code>Subnormal</code>]] are also signaled.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>decimal.</code><code>FloatOperation</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">decimal.</span></span><span class="sig-name descname"><span class="pre">FloatOperation</span></span></dt>
<dd><p>Enable stricter semantics for mixing floats and Decimals.</p>
+
<dd><p>为混合浮点数和小数启用更严格的语义。</p>
<p>If the signal is not trapped (default), mixing floats and Decimals is
+
<p>如果信号未被捕获(默认),则允许在 [[#decimal.Decimal|Decimal]] 构造函数、[[#decimal.Context.create_decimal|create_decimal()]] 和所有比较运算符中混合浮点数和小数。 转换和比较都是精确的。 通过在上下文标志中设置 [[#decimal.FloatOperation|FloatOperation]] 来静默记录混合操作的任何发生。 使用 [[#decimal.Decimal.from_float|from_float()]] [[#decimal.Context.create_decimal_from_float|create_decimal_from_float()]] 的显式转换不设置标志。</p>
permitted in the [[#decimal.Decimal|<code>Decimal</code>]] constructor,
+
<p>否则(信号被捕获),只有相等比较和显式转换是静默的。 所有其他混合操作引发 [[#decimal.FloatOperation|FloatOperation]]</p></dd></dl>
[[#decimal.Context.create_decimal|<code>create_decimal()</code>]] and all comparison operators.
 
Both conversion and comparisons are exact. Any occurrence of a mixed
 
operation is silently recorded by setting [[#decimal.FloatOperation|<code>FloatOperation</code>]] in the
 
context flags. Explicit conversions with [[#decimal.Decimal.from_float|<code>from_float()</code>]]
 
or [[#decimal.Context.create_decimal_from_float|<code>create_decimal_from_float()</code>]] do not set the flag.</p>
 
<p>Otherwise (the signal is trapped), only equality comparisons and explicit
 
conversions are silent. All other mixed operations raise [[#decimal.FloatOperation|<code>FloatOperation</code>]].</p></dd></dl>
 
  
The following table summarizes the hierarchy of signals:
+
下表总结了信号的层次结构:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,720行: 第1,346行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>exceptions.ArithmeticError(exceptions.Exception)
+
<syntaxhighlight lang="python3">exceptions.ArithmeticError(exceptions.Exception)
 
     DecimalException
 
     DecimalException
 
         Clamped
 
         Clamped
第1,730行: 第1,356行:
 
         Rounded
 
         Rounded
 
         Subnormal
 
         Subnormal
         FloatOperation(DecimalException, exceptions.TypeError)</pre>
+
         FloatOperation(DecimalException, exceptions.TypeError)</syntaxhighlight>
  
 
</div>
 
</div>
第1,740行: 第1,366行:
  
 
<span id="decimal-notes"></span>
 
<span id="decimal-notes"></span>
== Floating Point Notes ==
+
== 浮点注释 ==
  
 
<div id="mitigating-round-off-error-with-increased-precision" class="section">
 
<div id="mitigating-round-off-error-with-increased-precision" class="section">
  
=== Mitigating round-off error with increased precision ===
+
=== 以更高的精度减少舍入误差 ===
  
The use of decimal floating point eliminates decimal representation error
+
十进制浮点数的使用消除了十进制表示错误(可以准确表示<code>0.1</code>); 但是,当非零数字超过固定精度时,某些操作仍然会产生舍入误差。
(making it possible to represent <code>0.1</code> exactly); however, some operations
 
can still incur round-off error when non-zero digits exceed the fixed precision.
 
  
The effects of round-off error can be amplified by the addition or subtraction
+
舍入误差的影响可以通过增加或减少几乎抵消的量而放大,从而导致显着性损失。 Knuth 提供了两个有启发性的例子,其中精度不足的舍入浮点运算会导致加法的关联和分配属性崩溃:
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:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第1,760行: 第1,380行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre># Examples from Seminumerical Algorithms, Section 4.2.2.
+
<pre class="pycon3"># Examples from Seminumerical Algorithms, Section 4.2.2.
 
&gt;&gt;&gt; from decimal import Decimal, getcontext
 
&gt;&gt;&gt; from decimal import Decimal, getcontext
 
&gt;&gt;&gt; getcontext().prec = 8
 
&gt;&gt;&gt; getcontext().prec = 8
第1,779行: 第1,399行:
  
 
</div>
 
</div>
The [[#module-decimal|<code>decimal</code>]] module makes it possible to restore the identities by
+
[[#module-decimal|decimal]] 模块可以通过充分扩展精度来恢复身份,以避免丢失重要性:
expanding the precision sufficiently to avoid loss of significance:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第1,786行: 第1,405行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 20
+
<pre class="pycon3">&gt;&gt;&gt; getcontext().prec = 20
 
&gt;&gt;&gt; u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
 
&gt;&gt;&gt; u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
 
&gt;&gt;&gt; (u + v) + w
 
&gt;&gt;&gt; (u + v) + w
第1,806行: 第1,425行:
 
<div id="special-values" class="section">
 
<div id="special-values" class="section">
  
=== Special values ===
+
=== 特殊值 ===
  
The number system for the [[#module-decimal|<code>decimal</code>]] module provides special values
+
[[#module-decimal|decimal]] 模块的数字系统提供了特殊值,包括 <code>NaN</code><code>sNaN</code><code>-Infinity</code><code>Infinity</code> 和两个零,[ X143X] 和 <code>-0</code>
including <code>NaN</code>, <code>sNaN</code>, <code>-Infinity</code>, <code>Infinity</code>,
 
and two zeros, <code>+0</code> and <code>-0</code>.
 
  
Infinities can be constructed directly with: <code>Decimal('Infinity')</code>. Also,
+
无穷大可以直接构造为:<code>Decimal('Infinity')</code>。 此外,当 [[#decimal.DivisionByZero|DivisionByZero]] 信号未被捕获时,它们可能由除以零引起。 同样,当 [[#decimal.Overflow|Overflow]] 信号未被捕获时,四舍五入可能会导致超出最大可表示数限制的无穷大。
they can arise from dividing by zero when the [[#decimal.DivisionByZero|<code>DivisionByZero</code>]] signal is
 
not trapped. Likewise, when the [[#decimal.Overflow|<code>Overflow</code>]] signal is not trapped, infinity
 
can result from rounding beyond the limits of the largest representable number.
 
  
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 <code>NaN</code>, or if the
+
某些操作不确定并返回 <code>NaN</code>,或者如果 [[#decimal.InvalidOperation|InvalidOperation]] 信号被捕获,则引发异常。 例如,<code>0/0</code> 返回 <code>NaN</code>,表示“不是数字”。 这种 <code>NaN</code> 是安静的,一旦创建,将通过其他计算始终产生另一个 <code>NaN</code>。 此行为对于偶尔丢失输入的一系列计算很有用 - 它允许计算继续进行,同时将特定结果标记为无效。
[[#decimal.InvalidOperation|<code>InvalidOperation</code>]] signal is trapped, raise an exception. For example,
 
<code>0/0</code> returns <code>NaN</code> which means &quot;not a number&quot;. This variety of
 
<code>NaN</code> is quiet and, once created, will flow through other computations
 
always resulting in another <code>NaN</code>. This 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 <code>sNaN</code> which signals rather than remaining quiet after every
+
一个变体是 <code>sNaN</code>,它在每次操作后发出信号而不是保持安静。 当无效结果需要中断计算以进行特殊处理时,这是一个有用的返回值。
operation. 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
+
当涉及到 <code>NaN</code> 时,Python 的比较运算符的行为可能有点令人惊讶。 其中一个操作数是安静或信号 <code>NaN</code> 的相等性测试总是返回 [[../constants#False|False]](即使在执行 <code>Decimal('NaN')==Decimal('NaN')</code> 时),而不等性测试总是返回 [[constants.html#True|]真]]。 尝试使用 <code>&lt;</code><code>&lt;=</code><code>&gt;</code> <code>&gt;=</code> 运算符中的任何一个来比较两个小数将引发 [[#decimal.InvalidOperation|InvalidOperation]] 信号,如果任一操作数是 <code>NaN</code>,如果该信号未被捕获,则返回 [[../constants#False|False]]。 请注意,通用十进制算术规范没有指定直接比较的行为; 这些涉及 <code>NaN</code> 的比较规则取自 IEEE 854 标准(参见第 5.7 节中的表 3)。 为确保严格遵守标准,请改用 <code>compare()</code> <code>compare-signal()</code> 方法。
<code>NaN</code> is involved. A test for equality where one of the operands is a
 
quiet or signaling <code>NaN</code> always returns [[../constants#False|<code>False</code>]] (even when doing
 
<code>Decimal('NaN')==Decimal('NaN')</code>), while a test for inequality always returns
 
[[../constants#True|<code>True</code>]]. An attempt to compare two Decimals using any of the <code>&lt;</code>,
 
<code>&lt;=</code>, <code>&gt;</code> or <code>&gt;=</code> operators will raise the [[#decimal.InvalidOperation|<code>InvalidOperation</code>]] signal
 
if either operand is a <code>NaN</code>, and return [[../constants#False|<code>False</code>]] if this signal is
 
not trapped. Note that the General Decimal Arithmetic specification does not
 
specify the behavior of direct comparisons; these rules for comparisons
 
involving a <code>NaN</code> were taken from the IEEE 854 standard (see Table 3 in
 
section 5.7). To ensure strict standards-compliance, use the <code>compare()</code>
 
and <code>compare-signal()</code> methods instead.
 
  
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:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第1,861行: 第1,447行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; 1 / Decimal('Infinity')
+
<syntaxhighlight lang="python">>>> 1 / Decimal('Infinity')
Decimal('0E-1000026')</pre>
+
Decimal('0E-1000026')</syntaxhighlight>
  
 
</div>
 
</div>
第1,874行: 第1,460行:
  
 
<span id="decimal-threads"></span>
 
<span id="decimal-threads"></span>
== Working with threads ==
+
== 使用线程 ==
  
The [[#decimal.getcontext|<code>getcontext()</code>]] function accesses a different [[#decimal.Context|<code>Context</code>]] object for
+
[[#decimal.getcontext|getcontext()]] 函数为每个线程访问不同的 [[#decimal.Context|Context]] 对象。 拥有单独的线程上下文意味着线程可以在不干扰其他线程的情况下进行更改(例如 <code>getcontext().prec=10</code>)。
each thread. Having separate thread contexts means that threads may make
 
changes (such as <code>getcontext().prec=10</code>) without interfering with other threads.
 
  
Likewise, the [[#decimal.setcontext|<code>setcontext()</code>]] function automatically assigns its target to
+
同样,[[#decimal.setcontext|setcontext()]] 函数自动将其目标分配给当前线程。
the current thread.
 
  
If [[#decimal.setcontext|<code>setcontext()</code>]] has not been called before [[#decimal.getcontext|<code>getcontext()</code>]], then
+
如果 [[#decimal.setcontext|setcontext()]] [[#decimal.getcontext|getcontext()]] 之前没有被调用,那么 [[#decimal.getcontext|getcontext()]] 将自动创建一个新的上下文以供当前线程使用。
[[#decimal.getcontext|<code>getcontext()</code>]] will automatically create a new context for use in the
 
current thread.
 
  
The new context is copied from a prototype context called ''DefaultContext''. To
+
新的上下文是从名为 ''DefaultContext'' 的原型上下文中复制的。 要控制默认值以便每个线程在整个应用程序中使用相同的值,请直接修改 ''DefaultContext'' 对象。 这应该在 ''任何线程启动之前完成'' ,以便在调用 [[#decimal.getcontext|getcontext()]] 的线程之间不会出现竞争条件。 例如:
control the defaults so that each thread will use the same values throughout the
 
application, directly modify the ''DefaultContext'' object. This should be done
 
''before'' any threads are started so that there won't be a race condition between
 
threads calling [[#decimal.getcontext|<code>getcontext()</code>]]. For example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,897行: 第1,474行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre># Set applicationwide defaults for all threads about to be launched
+
<syntaxhighlight lang="python3"># Set applicationwide defaults for all threads about to be launched
 
DefaultContext.prec = 12
 
DefaultContext.prec = 12
 
DefaultContext.rounding = ROUND_DOWN
 
DefaultContext.rounding = ROUND_DOWN
第1,908行: 第1,485行:
 
t2.start()
 
t2.start()
 
t3.start()
 
t3.start()
  . . .</pre>
+
  . . .</syntaxhighlight>
  
 
</div>
 
</div>
第1,918行: 第1,495行:
  
 
<span id="decimal-recipes"></span>
 
<span id="decimal-recipes"></span>
== Recipes ==
+
== 食谱 ==
  
Here are a few recipes that serve as utility functions and that demonstrate ways
+
以下是一些用作实用函数并演示使用 [[#decimal.Decimal|Decimal]] 类的方法的方法:
to work with the [[#decimal.Decimal|<code>Decimal</code>]] class:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,927行: 第1,503行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def moneyfmt(value, places=2, curr='', sep=',', dp='.',
+
<syntaxhighlight lang="python3">def moneyfmt(value, places=2, curr='', sep=',', dp='.',
 
             pos='', neg='-', trailneg=''):
 
             pos='', neg='-', trailneg=''):
     &quot;&quot;&quot;Convert Decimal to a money formatted string.
+
     """Convert Decimal to a money formatted string.
  
 
     places:  required number of places after the decimal point
 
     places:  required number of places after the decimal point
第1,940行: 第1,516行:
 
     trailneg:optional trailing minus indicator:  '-', ')', space or blank
 
     trailneg:optional trailing minus indicator:  '-', ')', space or blank
  
     &gt;&gt;&gt; d = Decimal('-1234567.8901')
+
     >>> d = Decimal('-1234567.8901')
     &gt;&gt;&gt; moneyfmt(d, curr='$')
+
     >>> moneyfmt(d, curr='$')
 
     '-$1,234,567.89'
 
     '-$1,234,567.89'
     &gt;&gt;&gt; moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
+
     >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
 
     '1.234.568-'
 
     '1.234.568-'
     &gt;&gt;&gt; moneyfmt(d, curr='$', neg='(', trailneg=')')
+
     >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
 
     '($1,234,567.89)'
 
     '($1,234,567.89)'
     &gt;&gt;&gt; moneyfmt(Decimal(123456789), sep=' ')
+
     >>> moneyfmt(Decimal(123456789), sep=' ')
 
     '123 456 789.00'
 
     '123 456 789.00'
     &gt;&gt;&gt; moneyfmt(Decimal('-0.02'), neg='&lt;', trailneg='&gt;')
+
     >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
     '&lt;0.02&gt;'
+
     '<0.02>'
  
     &quot;&quot;&quot;
+
     """
     q = Decimal(10) ** -places      # 2 places --&gt; '0.01'
+
     q = Decimal(10) ** -places      # 2 places --> '0.01'
 
     sign, digits, exp = value.quantize(q).as_tuple()
 
     sign, digits, exp = value.quantize(q).as_tuple()
 
     result = []
 
     result = []
第1,978行: 第1,554行:
  
 
def pi():
 
def pi():
     &quot;&quot;&quot;Compute Pi to the current precision.
+
     """Compute Pi to the current precision.
  
     &gt;&gt;&gt; print(pi())
+
     >>> print(pi())
 
     3.141592653589793238462643383
 
     3.141592653589793238462643383
  
     &quot;&quot;&quot;
+
     """
 
     getcontext().prec += 2  # extra digits for intermediate steps
 
     getcontext().prec += 2  # extra digits for intermediate steps
     three = Decimal(3)      # substitute &quot;three=3.0&quot; for regular floats
+
     three = Decimal(3)      # substitute "three=3.0" for regular floats
 
     lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
 
     lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
 
     while s != lasts:
 
     while s != lasts:
第1,997行: 第1,573行:
  
 
def exp(x):
 
def exp(x):
     &quot;&quot;&quot;Return e raised to the power of x.  Result type matches input type.
+
     """Return e raised to the power of x.  Result type matches input type.
  
     &gt;&gt;&gt; print(exp(Decimal(1)))
+
     >>> print(exp(Decimal(1)))
 
     2.718281828459045235360287471
 
     2.718281828459045235360287471
     &gt;&gt;&gt; print(exp(Decimal(2)))
+
     >>> print(exp(Decimal(2)))
 
     7.389056098930650227230427461
 
     7.389056098930650227230427461
     &gt;&gt;&gt; print(exp(2.0))
+
     >>> print(exp(2.0))
 
     7.38905609893
 
     7.38905609893
     &gt;&gt;&gt; print(exp(2+0j))
+
     >>> print(exp(2+0j))
 
     (7.38905609893+0j)
 
     (7.38905609893+0j)
  
     &quot;&quot;&quot;
+
     """
 
     getcontext().prec += 2
 
     getcontext().prec += 2
 
     i, lasts, s, fact, num = 0, 0, 1, 1, 1
 
     i, lasts, s, fact, num = 0, 0, 1, 1, 1
第2,021行: 第1,597行:
  
 
def cos(x):
 
def cos(x):
     &quot;&quot;&quot;Return the cosine of x as measured in radians.
+
     """Return the cosine of x as measured in radians.
  
 
     The Taylor series approximation works best for a small value of x.
 
     The Taylor series approximation works best for a small value of x.
 
     For larger values, first compute x = x % (2 * pi).
 
     For larger values, first compute x = x % (2 * pi).
  
     &gt;&gt;&gt; print(cos(Decimal('0.5')))
+
     >>> print(cos(Decimal('0.5')))
 
     0.8775825618903727161162815826
 
     0.8775825618903727161162815826
     &gt;&gt;&gt; print(cos(0.5))
+
     >>> print(cos(0.5))
 
     0.87758256189
 
     0.87758256189
     &gt;&gt;&gt; print(cos(0.5+0j))
+
     >>> print(cos(0.5+0j))
 
     (0.87758256189+0j)
 
     (0.87758256189+0j)
  
     &quot;&quot;&quot;
+
     """
 
     getcontext().prec += 2
 
     getcontext().prec += 2
 
     i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
 
     i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
第2,047行: 第1,623行:
  
 
def sin(x):
 
def sin(x):
     &quot;&quot;&quot;Return the sine of x as measured in radians.
+
     """Return the sine of x as measured in radians.
  
 
     The Taylor series approximation works best for a small value of x.
 
     The Taylor series approximation works best for a small value of x.
 
     For larger values, first compute x = x % (2 * pi).
 
     For larger values, first compute x = x % (2 * pi).
  
     &gt;&gt;&gt; print(sin(Decimal('0.5')))
+
     >>> print(sin(Decimal('0.5')))
 
     0.4794255386042030002732879352
 
     0.4794255386042030002732879352
     &gt;&gt;&gt; print(sin(0.5))
+
     >>> print(sin(0.5))
 
     0.479425538604
 
     0.479425538604
     &gt;&gt;&gt; print(sin(0.5+0j))
+
     >>> print(sin(0.5+0j))
 
     (0.479425538604+0j)
 
     (0.479425538604+0j)
  
     &quot;&quot;&quot;
+
     """
 
     getcontext().prec += 2
 
     getcontext().prec += 2
 
     i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
 
     i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
第2,070行: 第1,646行:
 
         s += num / fact * sign
 
         s += num / fact * sign
 
     getcontext().prec -= 2
 
     getcontext().prec -= 2
     return +s</pre>
+
     return +s</syntaxhighlight>
  
 
</div>
 
</div>
第2,079行: 第1,655行:
 
<div id="decimal-faq" class="section">
 
<div id="decimal-faq" class="section">
  
<span id="id1"></span>
+
<span id="id3"></span>
== Decimal FAQ ==
+
== 十进制常见问题 ==
 
 
Q. It is cumbersome to type <code>decimal.Decimal('1234.5')</code>. Is there a way to
 
minimize typing when using the interactive interpreter?
 
  
A. Some users abbreviate the constructor to just a single letter:
+
问。 输入<code>decimal.Decimal('1234.5')</code>很麻烦。 有没有办法在使用交互式解释器时尽量减少打字?
  
 +
<ol>
 +
<li><p>一些用户将构造函数缩写为一个字母:</p>
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; D = decimal.Decimal
+
<syntaxhighlight lang="python">>>> D = decimal.Decimal
&gt;&gt;&gt; D('1.23') + D('3.45')
+
>>> D('1.23') + D('3.45')
Decimal('4.68')</pre>
+
Decimal('4.68')</syntaxhighlight>
  
 
</div>
 
</div>
  
</div>
+
</div></li></ol>
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 <code>quantize()</code> method rounds to a fixed number of decimal places. If
+
一种。 <code>quantize()</code> 方法四舍五入到固定的小数位数。 如果设置了 [[#decimal.Inexact|Inexact]] 陷阱,它也可用于验证:
the [[#decimal.Inexact|<code>Inexact</code>]] trap is set, it is also useful for validation:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第2,109行: 第1,682行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; TWOPLACES = Decimal(10) ** -2      # same as Decimal('0.01')</pre>
+
<syntaxhighlight lang="python">>>> TWOPLACES = Decimal(10) ** -2      # same as Decimal('0.01')</syntaxhighlight>
  
 
</div>
 
</div>
第2,118行: 第1,691行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # Round to two places
+
<syntaxhighlight lang="python">>>> # Round to two places
&gt;&gt;&gt; Decimal('3.214').quantize(TWOPLACES)
+
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')</pre>
+
Decimal('3.21')</syntaxhighlight>
  
 
</div>
 
</div>
第2,129行: 第1,702行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # Validate that a number does not exceed two places
+
<syntaxhighlight lang="python">>>> # Validate that a number does not exceed two places
&gt;&gt;&gt; Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
+
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')</pre>
+
Decimal('3.21')</syntaxhighlight>
  
 
</div>
 
</div>
第2,140行: 第1,713行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
+
<syntaxhighlight lang="python">>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
 
Traceback (most recent call last):
 
Traceback (most recent call last):
 
   ...
 
   ...
Inexact: None</pre>
+
Inexact: None</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
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
+
一种。 一些运算,如加法、减法和乘以整数会自动保留不动点。 其他运算,如除法和非整数乘法,会改变小数位数,需要跟上 <code>quantize()</code> 步:
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 <code>quantize()</code> step:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第2,160行: 第1,729行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; a = Decimal('102.72')          # Initial fixed-point values
+
<syntaxhighlight lang="python">>>> a = Decimal('102.72')          # Initial fixed-point values
&gt;&gt;&gt; b = Decimal('3.17')
+
>>> b = Decimal('3.17')
&gt;&gt;&gt; a + b                          # Addition preserves fixed-point
+
>>> a + b                          # Addition preserves fixed-point
 
Decimal('105.89')
 
Decimal('105.89')
&gt;&gt;&gt; a - b
+
>>> a - b
 
Decimal('99.55')
 
Decimal('99.55')
&gt;&gt;&gt; a * 42                          # So does integer multiplication
+
>>> a * 42                          # So does integer multiplication
 
Decimal('4314.24')
 
Decimal('4314.24')
&gt;&gt;&gt; (a * b).quantize(TWOPLACES)    # Must quantize non-integer multiplication
+
>>> (a * b).quantize(TWOPLACES)    # Must quantize non-integer multiplication
 
Decimal('325.62')
 
Decimal('325.62')
&gt;&gt;&gt; (b / a).quantize(TWOPLACES)    # And quantize division
+
>>> (b / a).quantize(TWOPLACES)    # And quantize division
Decimal('0.03')</pre>
+
Decimal('0.03')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In developing fixed-point applications, it is convenient to define functions
+
在开发定点应用时,可以方便地定义处理<code>quantize()</code>步骤的函数:
to handle the <code>quantize()</code> step:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第2,183行: 第1,751行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def mul(x, y, fp=TWOPLACES):
+
<syntaxhighlight lang="python">>>> def mul(x, y, fp=TWOPLACES):
 
...    return (x * y).quantize(fp)
 
...    return (x * y).quantize(fp)
&gt;&gt;&gt; def div(x, y, fp=TWOPLACES):
+
>>> def div(x, y, fp=TWOPLACES):
...    return (x / y).quantize(fp)</pre>
+
...    return (x / y).quantize(fp)</syntaxhighlight>
  
 
</div>
 
</div>
第2,195行: 第1,763行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; mul(a, b)                      # Automatically preserve fixed-point
+
<syntaxhighlight lang="python">>>> mul(a, b)                      # Automatically preserve fixed-point
 
Decimal('325.62')
 
Decimal('325.62')
&gt;&gt;&gt; div(b, a)
+
>>> div(b, a)
Decimal('0.03')</pre>
+
Decimal('0.03')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Q. There are many ways to express the same value. The numbers <code>200</code>,
+
问。 有很多方法可以表达相同的值。 数字 <code>200</code><code>200.000</code><code>2E2</code> <code>02E+4</code> 在不同的精度下都具有相同的值。 有没有办法将它们转换为单个可识别的规范值?
<code>200.000</code>, <code>2E2</code>, and <code>02E+4</code> all have the same value at
 
various precisions. Is there a way to transform them to a single recognizable
 
canonical value?
 
  
A. The <code>normalize()</code> method maps all equivalent values to a single
+
一种。 <code>normalize()</code> 方法将所有等效值映射到单个代表:
representative:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第2,215行: 第1,779行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
+
<syntaxhighlight lang="python">>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
&gt;&gt;&gt; [v.normalize() for v in values]
+
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]</pre>
+
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
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
+
一种。 对于某些值,指数表示法是表示系数中重要位置数的唯一方法。 例如,将 <code>5.0E+3</code> 表示为 <code>5000</code> 可以保持值不变,但不能显示原始的两位重要性。
of significant places in the coefficient. For example, expressing
 
<code>5.0E+3</code> as <code>5000</code> keeps the value constant but cannot show the
 
original's two-place significance.
 
  
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:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第2,238行: 第1,796行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def remove_exponent(d):
+
<syntaxhighlight lang="python">>>> def remove_exponent(d):
...    return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()</pre>
+
...    return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()</syntaxhighlight>
  
 
</div>
 
</div>
第2,248行: 第1,806行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; remove_exponent(Decimal('5E+3'))
+
<syntaxhighlight lang="python">>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')</pre>
+
Decimal('5000')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Q. Is there a way to convert a regular float to a [[#decimal.Decimal|<code>Decimal</code>]]?
+
<ol start="17">
 +
<li><p>有没有办法将常规浮点数转换为 [[#decimal.Decimal|十进制]] ?</p></li></ol>
  
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:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第2,264行: 第1,821行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal(math.pi)
+
<pre class="pycon3">&gt;&gt;&gt; Decimal(math.pi)
 
Decimal('3.141592653589793115997963468544185161590576171875')</pre>
 
Decimal('3.141592653589793115997963468544185161590576171875')</pre>
  
第2,270行: 第1,827行:
  
 
</div>
 
</div>
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 &quot;what you type is what you get&quot;. A disadvantage is that the
 
results can look odd if you forget that the inputs haven't been rounded:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第2,291行: 第1,839行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 3
+
<pre class="pycon3">&gt;&gt;&gt; getcontext().prec = 3
 
&gt;&gt;&gt; Decimal('3.104') + Decimal('2.104')
 
&gt;&gt;&gt; Decimal('3.104') + Decimal('2.104')
 
Decimal('5.21')
 
Decimal('5.21')
第2,300行: 第1,848行:
  
 
</div>
 
</div>
The solution is either to increase precision or to force rounding of inputs
+
解决方案是提高精度或使用一元加运算强制舍入输入:
using the unary plus operation:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第2,307行: 第1,854行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getcontext().prec = 3
+
<pre class="pycon3">&gt;&gt;&gt; getcontext().prec = 3
 
&gt;&gt;&gt; +Decimal('1.23456789')      # unary plus triggers rounding
 
&gt;&gt;&gt; +Decimal('1.23456789')      # unary plus triggers rounding
 
Decimal('1.23')</pre>
 
Decimal('1.23')</pre>
第2,314行: 第1,861行:
  
 
</div>
 
</div>
Alternatively, inputs can be rounded upon creation using the
+
或者,可以使用 [[#decimal.Context.create_decimal|Context.create_decimal()]] 方法在创建时舍入输入:
[[#decimal.Context.create_decimal|<code>Context.create_decimal()</code>]] method:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第2,321行: 第1,867行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
+
<syntaxhighlight lang="python">>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')</pre>
+
Decimal('1.2345')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Q. Is the CPython implementation fast for large numbers?
+
<ol start="17">
 +
<li><p>CPython 实现对于大量数据是否快速?</p></li></ol>
  
A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of
+
一种。 是的。 在 CPython PyPy3 实现中,十进制模块的 C/CFFI 版本集成了高速 [https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html libmpdec] 库,用于任意精度的正确舍入十进制浮点运算 [[#id6|1]]<code>libmpdec</code> 使用 [https://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba 乘法] 处理中等大小的数字,使用 [https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform 数论变换] 处理非常大的数字。
the decimal module integrate the high speed [https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html libmpdec] library for
 
arbitrary precision correctly-rounded decimal floating point arithmetic [[#id4|1]].
 
<code>libmpdec</code> uses [https://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba multiplication]
 
for medium-sized numbers and the [https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform Number Theoretic Transform]
 
for very large numbers.
 
  
The context must be adapted for exact arbitrary precision arithmetic. <code>Emin</code>
+
上下文必须适用于精确的任意精度算术。 <code>Emin</code> <code>Emax</code> 应始终设置为最大值,<code>clamp</code> 应始终为 0(默认值)。 设置 <code>prec</code> 需要小心。
and <code>Emax</code> should always be set to the maximum values, <code>clamp</code>
 
should always be 0 (the default). Setting <code>prec</code> requires some care.
 
  
The easiest approach for trying out bignum arithmetic is to use the maximum
+
尝试 bignum 算法的最简单方法是使用 <code>prec</code> [[#id7|2]] 的最大值:
value for <code>prec</code> as well [[#id5|2]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,347行: 第1,886行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
+
<syntaxhighlight lang="python3">>>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
&gt;&gt;&gt; x = Decimal(2) ** 256
+
>>> x = Decimal(2) ** 256
&gt;&gt;&gt; x / 128
+
>>> x / 128
Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')</pre>
+
Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For inexact results, [[#decimal.MAX_PREC|<code>MAX_PREC</code>]] is far too large on 64-bit platforms and
+
对于不精确的结果,[[#decimal.MAX_PREC|MAX_PREC]] 64 位平台上太大了,可用内存不足:
the available memory will be insufficient:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,362行: 第1,900行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Decimal(1) / 3
+
<syntaxhighlight lang="python3">>>> Decimal(1) / 3
 
Traceback (most recent call last):
 
Traceback (most recent call last):
   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
+
   File "<stdin>", line 1, in <module>
MemoryError</pre>
+
MemoryError</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
On systems with overallocation (e.g. Linux), a more sophisticated approach is to
+
在过度分配的系统上(例如 Linux),更复杂的方法是根据可用 RAM 量调整 <code>prec</code>。 假设您有 8GB RAM 并期望有 10 个同时操作数,每个操作数最多使用 500MB:
adjust <code>prec</code> to the amount of available RAM. Suppose that you have 8GB of
 
RAM and expect 10 simultaneous operands using a maximum of 500MB each:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,378行: 第1,914行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import sys
+
<syntaxhighlight lang="python3">>>> import sys
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # Maximum number of digits for a single operand using 500MB in 8-byte words
+
>>> # Maximum number of digits for a single operand using 500MB in 8-byte words
&gt;&gt;&gt; # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
+
>>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
&gt;&gt;&gt; maxdigits = 19 * ((500 * 1024**2) // 8)
+
>>> maxdigits = 19 * ((500 * 1024**2) // 8)
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # Check that this works:
+
>>> # Check that this works:
&gt;&gt;&gt; c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
+
>>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
&gt;&gt;&gt; c.traps[Inexact] = True
+
>>> c.traps[Inexact] = True
&gt;&gt;&gt; setcontext(c)
+
>>> setcontext(c)
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # Fill the available precision with nines:
+
>>> # Fill the available precision with nines:
&gt;&gt;&gt; x = Decimal(0).logical_invert() * 9
+
>>> x = Decimal(0).logical_invert() * 9
&gt;&gt;&gt; sys.getsizeof(x)
+
>>> sys.getsizeof(x)
 
524288112
 
524288112
&gt;&gt;&gt; x + 2
+
>>> x + 2
 
Traceback (most recent call last):
 
Traceback (most recent call last):
   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
+
   File "<stdin>", line 1, in <module>
   decimal.Inexact: [&lt;class 'decimal.Inexact'&gt;]</pre>
+
   decimal.Inexact: [<class 'decimal.Inexact'>]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In general (and especially on systems without overallocation), it is recommended
+
一般来说(尤其是在没有过度分配的系统上),如果希望所有计算都是准确的,建议估计更严格的界限并设置 [[#decimal.Inexact|不精确]] 陷阱。
to estimate even tighter bounds and set the [[#decimal.Inexact|<code>Inexact</code>]] trap if all calculations
 
are expected to be exact.
 
  
 
<dl>
 
<dl>
<dt><span class="brackets">[[#id2|1]]</span></dt>
+
<dt><span class="brackets">[[#id4|1]]</span></dt>
 
<dd><div class="versionadded">
 
<dd><div class="versionadded">
  
<p><span class="versionmodified added">3.3 新版功能.</span></p>
+
<p><span class="versionmodified added">3.3 版中的新功能。</span></p>
  
 
</div></dd>
 
</div></dd>
<dt><span class="brackets">[[#id3|2]]</span></dt>
+
<dt><span class="brackets">[[#id5|2]]</span></dt>
 
<dd><div class="versionchanged">
 
<dd><div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>This approach now works for all exact results except for non-integer powers.</p>
+
<p><span class="versionmodified changed"> 3.9 版更改: </span> 这种方法现在适用于除非整数幂以外的所有精确结果。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第2,421行: 第1,955行:
  
 
</div>
 
</div>
 +
 +
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

decimal — 十进制定点和浮点运算

源代码: :source:`Lib/decimal.py`



decimal 模块支持快速正确舍入的十进制浮点运算。 与 float 数据类型相比,它具有以下几个优点:

  • 十进制“基于浮点模型,该模型是为人而设计的,并且必然具有最重要的指导原则——计算机必须提供一种与人们在学校学习的算术相同的算术。” – 摘自十进制算术规范。

  • 十进制数可以精确表示。 相比之下,像 1.12.2 这样的数字在二进制浮点数中没有精确的表示。 最终用户通常不希望 1.1 + 2.2 显示为 3.3000000000000003,因为它与二进制浮点数一样。

  • 精确性延续到算术中。 在十进制浮点数中,0.1 + 0.1 + 0.1 - 0.3 正好等于零。 在二进制浮点中,结果是 5.5511151231257827e-017。 虽然接近于零,但差异阻止了可靠的相等性测试,并且差异可能会累积。 出于这个原因,十进制在具有严格等式不变量的会计应用程序中是首选。

  • 十进制模块包含重要位置的概念,因此 1.30 + 1.202.50。 保留尾随零以指示重要性。 这是货币应用程序的惯用表示。 对于乘法,“教科书”方法使用被乘数中的所有数字。 例如,1.3 * 1.2 给出 1.56,而 1.30 * 1.20 给出 1.5600

  • 与基于硬件的二进制浮点数不同,decimal 模块具有用户可更改的精度(默认为 28 位),该精度可以根据给定问题的需要而定:

    >>> from decimal import *
    >>> getcontext().prec = 6
    >>> Decimal(1) / Decimal(7)
    Decimal('0.142857')
    >>> getcontext().prec = 28
    >>> Decimal(1) / Decimal(7)
    Decimal('0.1428571428571428571428571429')
  • 二进制和十进制浮点数都是根据已发布的标准实现的。 虽然内置 float 类型仅公开了其功能的一小部分,但 decimal 模块公开了标准的所有必需部分。 需要时,程序员可以完全控制舍入和信号处理。 这包括通过使用异常来阻止任何不精确操作来强制执行精确算术的选项。

  • 十进制模块旨在支持“无偏见的精确未舍入十进制算术(有时称为定点算术)和舍入浮点算术”。 – 摘自十进制算术规范。

模块设计以三个概念为中心:十进制数、算术上下文和信号。

十进制数是不可变的。 它有一个符号、系数数字和一个指数。 为了保持显着性,系数数字不会截断尾随零。 小数还包括特殊值,例如 Infinity-InfinityNaN。 该标准还将 -0+0 区分开来。

算术的上下文是指定精度、舍入规则、指数限制、指示运算结果的标志以及确定信号是否被视为异常的陷阱启动器的环境。 舍入选项包括 ROUND_CEILINGROUND_DOWNROUND_FLOORROUND_HALF_DOWN、ROUND_HALF_X64X1X1X1X14 、ROUND_UPROUND_05UP

信号是在计算过程中出现的一组异常情况。 根据应用程序的需要,信号可能会被忽略,被视为信息,或被视为异常。 十进制模块中的信号有:ClampedInvalidOperationDivisionByZeroInexactRounded、 ]次正常、溢出下溢FloatOperation

对于每个信号,都有一个标志和一个陷阱使能器。 当遇到信号时,其标志设置为 1,然后,如果陷阱启用器设置为 1,则会引发异常。 标志是粘性的,因此用户需要在监视计算之前重置它们。

也可以看看


快速入门教程

使用小数的通常开始是导入模块,使用 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 实例可以由整数、字符串、浮点数或元组构成。 从整数或浮点数构造执行该整数或浮点数的值的精确转换。 十进制数包括特殊值,例如代表“非数字”的 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')

如果 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

3.3 版中的新功能。


新十进制的重要性仅由输入的位数决定。 上下文精度和舍入仅在算术运算期间起作用。

>>> 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')

如果超出 C 版本的内部限制,则构造一个小数会引发 InvalidOperation

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

在 3.3 版中更改。


Decimals 可以与 Python 的其他大部分内容很好地交互。 这是一个小十进制浮点飞行马戏团:

>>> 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')

一些数学函数也可用于 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')

quantize() 方法将数字四舍五入为固定指数。 此方法对于经常将结果四舍五入到固定数量位置的货币应用程序很有用:

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

如上所示,getcontext() 函数访问当前上下文并允许更改设置。 这种方法可以满足大多数应用程序的需求。

对于更高级的工作,使用 Context() 构造函数创建备用上下文可能很有用。 要激活备用,请使用 setcontext() 函数。

根据标准,decimal 模块提供了两个随时可用的标准上下文,BasicContextExtendedContext。 前者对于调试特别有用,因为许多陷阱都已启用:

>>> 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

上下文还具有用于监视计算过程中遇到的异常情况的信号标志。 标志保持设置直到明确清除,因此最好在每组受监控计算之前使用 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=[])

flags 条目显示 Pi 的有理近似值被四舍五入(超出上下文精度的数字被丢弃)并且结果不准确(一些被丢弃的数字是非零的) .

使用上下文的 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

大多数程序仅在程序开始时调整当前上下文一次。 而且,在许多应用程序中,通过在循环内进行一次强制转换,数据会被转换为 Decimal。 创建上下文集和小数后,程序的大部分处理数据与其他 Python 数字类型没有什么不同。


十进制对象

class decimal.Decimal(value='0', context=None)

根据 构造一个新的 Decimal 对象。

value 可以是整数、字符串、元组、float 或另一个 Decimal 对象。 如果没有给出 value,则返回 Decimal('0')。 如果 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

digit 出现在上面的地方也允许使用其他 Unicode 十进制数字。 这些包括来自各种其他字母表的十进制数字(例如,阿拉伯-印度语和梵文数字)以及全角数字 '\uff10''\uff19'

如果 value 是一个 元组 ,它应该具有三个分量,一个符号(0 为正或 1 为负),一个 元组 的数字和整数指数。 例如,Decimal((0, (1, 4, 1, 4), -3)) 返回 Decimal('1.414')

如果 valuefloat,则二进制浮点值将无损地转换为其精确的十进制等效值。 这种转换通常需要 53 位或更多位的精度。 例如,Decimal(float('1.1')) 转换为 Decimal('1.100000000000000088817841970012523233890533447265625')

context 精度不影响存储的位数。 这完全由 中的位数决定。 例如,即使上下文精度只有三个,Decimal('3.00000') 也会记录所有五个零。

context 参数的目的是确定如果 value 是格式错误的字符串,该怎么办。 如果上下文捕获 InvalidOperation,则会引发异常; 否则,构造函数返回一个新的 Decimal,其值为 NaN

一旦构造,Decimal 对象是不可变的。

3.2 版更改: 现在允许构造函数的参数是 float 实例。

在 3.3 版中更改:如果设置了 FloatOperation 陷阱,则 float 参数会引发异常。 默认情况下,陷阱是关闭的。

3.6 版更改: 允许使用下划线进行分组,就像代码中的整数和浮点文字一样。

十进制浮点对象与其他内置数字类型共享许多属性,例如 floatint。 所有常用的数学运算和特殊方法都适用。 同样,十进制对象可以被复制、腌制、打印、用作字典键、用作集合元素、比较、排序和强制转换为另一种类型(例如 floatint) .

Decimal 对象的算术与整数和浮点数的算术之间存在一些细微差别。 当余数运算符 % 应用于 Decimal 对象时,结果的符号是 dividend 的符号而不是除数的符号:

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

整数除法运算符 // 的行为类似,返回真商的整数部分(向零截断)而不是其底,以保留通常的恒等式 x == (x // y) * y + x % y

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

%// 运算符实现了 remainderdivide-integer 操作(分别),如规范中所述。

在算术运算中,小数对象通常不能与浮点数或 fractions.Fraction 的实例组合:例如,尝试将 Decimal 添加到 float 将引发 TypeError。 但是,可以使用 Python 的比较运算符将 Decimal 实例 x 与另一个数字 y 进行比较。 这避免了在不同类型的数字之间进行相等比较时的混淆结果。

3.2 版更改: 现在完全支持 Decimal 实例和其他数字类型之间的混合类型比较。

除了标准的数字属性之外,十进制浮点对象还有许多专门的方法:

adjusted()

在移出系数最右边的数字后返回调整后的指数,直到只剩下前导数字:Decimal('321e+5').adjusted() 返回七。 用于确定最高有效数字相对于小数点的位置。

as_integer_ratio()

返回一对 (n, d) 整数,这些整数将给定的 Decimal 实例表示为分数,以最低项和正分母表示:

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

转换是准确的。 在无穷大上引发 OverflowError 并在 NaN 上引发 ValueError。

3.6 版中的新功能。

as_tuple()

返回数字的 命名元组 表示:DecimalTuple(sign, digits, exponent)

canonical()

返回参数的规范编码。 目前,Decimal 实例的编码始终是规范的,因此此操作返回其参数不变。

compare(other, context=None)

比较两个 Decimal 实例的值。 compare() 返回一个 Decimal 实例,如果任一操作数为 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)

此操作与 compare() 方法相同,只是所有 NaN 都发出信号。 也就是说,如果两个操作数都不是信号 NaN,则任何安静的 NaN 操作数都被视为信号 NaN。

compare_total(other, context=None)

使用它们的抽象表示而不是它们的数值比较两个操作数。 类似于 compare() 方法,但结果给出了 Decimal 实例的总排序。 具有相同数值但不同表示形式的两个 Decimal 实例在此排序中比较不相等:

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

Quiet 和 Signaling NaN 也包含在总排序中。 如果两个操作数具有相同的表示形式,则此函数的结果为 Decimal('0'),如果第一个操作数在总顺序中低于第二个,则为 Decimal('-1'),如果第一个操作数的顺序为 Decimal('1')操作数的总顺序高于第二个操作数。 有关总订单的详细信息,请参阅规范。

此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。

compare_total_mag(other, context=None)

使用它们的抽象表示而不是它们的值来比较两个操作数,如 compare_total(),但忽略每个操作数的符号。 x.compare_total_mag(y) 相当于 x.copy_abs().compare_total(y.copy_abs())

此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。

conjugate()

只返回self,此方法仅符合Decimal Specification。

copy_abs()

返回参数的绝对值。 此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。

copy_negate()

返回参数的否定。 此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。

copy_sign(other, context=None)

返回第一个操作数的副本,其符号设置为与第二个操作数的符号相同。 例如:

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

此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。

exp(context=None)

返回给定数字的(自然)指数函数 e**x 的值。 结果使用 ROUND_HALF_EVEN 舍入模式正确舍入。

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

准确地将浮点数转换为十进制数的类方法。

注意 Decimal.from_float(0.1) 与 Decimal('0.1') 不同。 由于 0.1 不能用二进制浮点精确表示,因此该值存储为最接近的可表示值,即 0x1.999999999999ap-4。 十进制的等效值是 0.1000000000000000055511151231257827021181583404541015625。

笔记

从 Python 3.2 开始,Decimal 实例也可以直接从 float 构造。

>>> 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')

3.1 版中的新功能。

fma(other, third, context=None)

融合乘加。 返回 self*other+third ,中间产品 self*other 没有四舍五入。

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

如果参数是规范的,则返回 True,否则返回 False。 目前,Decimal 实例总是规范的,所以这个操作总是返回 True

is_finite()

如果参数是有限数,则返回 True,如果参数是无穷大或 NaN,则返回 False

is_infinite()

如果参数是正无穷大或负无穷大,则返回 True,否则返回 False

is_nan()

如果参数是(安静或信号)NaN,则返回 True,否则返回 False

is_normal(context=None)

如果参数是 normal 有限数,则返回 True。 如果参数为零、次正规、无穷大或 NaN,则返回 False

is_qnan()

如果参数是安静的 NaN,则返回 True,否则返回 False

is_signed()

如果参数有负号,则返回 True,否则返回 False。 请注意,零和 NaN 都可以带有符号。

is_snan()

如果参数是信号 NaN,则返回 True,否则返回 False

is_subnormal(context=None)

如果参数不正常,则返回 True,否则返回 False

is_zero()

如果参数是(正或负)零,则返回 True,否则返回 False

ln(context=None)

返回操作数的自然(以 e 为底)对数。 结果使用 ROUND_HALF_EVEN 舍入模式正确舍入。

log10(context=None)

返回操作数的以 10 为底的对数。 结果使用 ROUND_HALF_EVEN 舍入模式正确舍入。

logb(context=None)

对于非零数,将其操作数的调整指数作为 Decimal 实例返回。 如果操作数为零,则返回 Decimal('-Infinity') 并引发 DivisionByZero 标志。 如果操作数是无穷大,则返回 Decimal('Infinity')

logical_and(other, context=None)

logical_and() 是一个逻辑运算,它采用两个 逻辑操作数 (请参阅 逻辑操作数 )。 结果是两个操作数的数字 and

logical_invert(context=None)

logical_invert() 是逻辑运算。 结果是操作数的数字反转。

logical_or(other, context=None)

logical_or() 是一个逻辑运算,它采用两个 逻辑操作数 (请参阅 逻辑操作数 )。 结果是两个操作数的数字 or

logical_xor(other, context=None)

logical_xor() 是一个逻辑运算,它采用两个 逻辑操作数 (参见 逻辑操作数 )。 结果是两个操作数的逐位异或。

max(other, context=None)

max(self, other) 类似,除了在返回之前应用上下文舍入规则,并且 NaN 值要么发出信号要么忽略(取决于上下文以及它们是发出信号还是静默)。

max_mag(other, context=None)

类似于 max() 方法,但比较是使用操作数的绝对值完成的。

min(other, context=None)

min(self, other) 类似,除了在返回之前应用上下文舍入规则,并且 NaN 值要么发出信号要么忽略(取决于上下文以及它们是发出信号还是静默)。

min_mag(other, context=None)

类似于 min() 方法,但比较是使用操作数的绝对值完成的。

next_minus(context=None)

返回在给定上下文(如果没有给定上下文,则在当前线程的上下文)中小于给定操作数的最大可表示数。

next_plus(context=None)

返回在给定上下文(如果没有给定上下文,则在当前线程的上下文)中大于给定操作数的可表示的最小数字。

next_toward(other, context=None)

如果两个操作数不相等,则返回在第二个操作数的方向上最接近第一个操作数的数字。 如果两个操作数在数值上相等,则返回第一个操作数的副本,其符号设置为与第二个操作数的符号相同。

normalize(context=None)

通过去除最右边的尾随零并将等于 Decimal('0') 的任何结果转换为 Decimal('0e0') 来标准化数字。 用于为等价类的属性生成规范值。 例如,Decimal('32.100')Decimal('0.321000e+2') 都归一化为等效值 Decimal('32.1')

number_class(context=None)

返回描述操作数的 的字符串。 返回值是以下十个字符串之一。

  • "-Infinity",表示操作数为负无穷大。

  • "-Normal",表示操作数为负数。

  • "-Subnormal",表示操作数为负数,次正规。

  • "-Zero",表示操作数为负零。

  • "+Zero",表示操作数为正零。

  • "+Subnormal",表示操作数为正,次正规。

  • "+Normal",表示操作数为正数。

  • "+Infinity",表示操作数为正无穷大。

  • "NaN",表示操作数是一个安静的 NaN(Not a Number)。

  • "sNaN",表示操作数为信令NaN。

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

在舍入并具有第二个操作数的指数后返回等于第一个操作数的值。

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

与其他操作不同,如果量化操作后系数的长度大于精度,则会发出 InvalidOperation 信号。 这保证了除非出现错误条件,否则量化指数始终等于右侧操作数的指数。

同样与其他操作不同的是,量化从不发出下溢信号,即使结果不正常且不准确。

如果第二个操作数的指数大于第一个的指数,则可能需要舍入。 在这种情况下,舍入模式由 rounding 参数决定,否则由 context 参数决定; 如果两个参数都没有给出,则使用当前线程上下文的舍入模式。

只要结果指数大于 Emax 或小于 Etiny,就会返回错误。

radix()

返回 Decimal(10)Decimal 类执行其所有算术的基数(基数)。 包括在内是为了与规范兼容。

remainder_near(other, context=None)

返回将 self 除以 other 的余数。 这与 self % other 的不同之处在于余数的符号被选择为使其绝对值最小。 更准确地说,返回值是 self - n * other,其中 n 是最接近 self / other 确切值的整数,如果两个整数相等,则选择偶数。

如果结果为零,则其符号将是 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)

返回按第二个操作数指定的量旋转第一个操作数的数字的结果。 第二个操作数必须是从 -precision 到 precision 范围内的整数。 第二个操作数的绝对值给出了要旋转的位置数。 如果第二个操作数为正,则向左旋转; 否则向右旋转。 如有必要,第一个操作数的系数在左侧填充零以达到长度精度。 第一个操作数的符号和指数不变。

same_quantum(other, context=None)

测试 self 和 other 是否具有相同的指数或两者是否都是 NaN

此操作不受上下文影响并且是安静的:不更改标志且不执行舍入。 作为一个例外,如果无法准确转换第二个操作数,C 版本可能会引发 InvalidOperation。

scaleb(other, context=None)

返回第一个操作数,其指数由第二个调整。 等效地,返回乘以 10**other 的第一个操作数。 第二个操作数必须是整数。

shift(other, context=None)

返回按第二个操作数指定的量移动第一个操作数的数字的结果。 第二个操作数必须是从 -precision 到 precision 范围内的整数。 第二个操作数的绝对值给出了要移位的位数。 如果第二个操作数为正,则向左移位; 否则向右移动。 移入系数的数字为零。 第一个操作数的符号和指数不变。

sqrt(context=None)

将参数的平方根返回到全精度。

to_eng_string(context=None)

如果需要指数,则使用工程符号转换为字符串。

工程符号的指数是 3 的倍数。 这最多可以在小数位左侧留下 3 位数字,并且可能需要添加一个或两个尾随零。

例如,这将 Decimal('123E+1') 转换为 Decimal('1.23E+3')

to_integral(rounding=None, context=None)

to_integral_value() 方法相同。 保留 to_integral 名称是为了与旧版本兼容。

to_integral_exact(rounding=None, context=None)

舍入到最接近的整数,如果发生舍入,则根据需要发出 不精确舍入 信号。 如果给定,舍入模式由 rounding 参数确定,否则由给定的 context 确定。 如果没有给出参数,则使用当前上下文的舍入模式。

to_integral_value(rounding=None, context=None)

舍入到最接近的整数而不用信号 InexactRounded。 如果给定,则应用 rounding; 否则,在提供的 context 或当前上下文中使用舍入方法。

逻辑操作数

logical_and()logical_invert()logical_or()logical_xor() 方法期望它们的参数是 逻辑操作数逻辑操作数是一个Decimal实例,其指数和符号都为零,并且其数字都是01


上下文对象

上下文是算术运算的环境。 它们控制精度、设置舍入规则、确定哪些信号被视为例外,并限制指数的范围。

每个线程都有自己的当前上下文,可以使用 getcontext()setcontext() 函数访问或更改:

decimal.getcontext()
返回活动线程的当前上下文。
decimal.setcontext(c)
将活动线程的当前上下文设置为 c

您还可以使用 with 语句和 localcontext() 函数来临时更改活动上下文。

decimal.localcontext(ctx=None)

返回一个上下文管理器,它将在进入 with-语句时将活动线程的当前上下文设置为 ctx 的副本,并在退出 with-语句时恢复先前的上下文。 如果未指定上下文,则使用当前上下文的副本。

例如,下面的代码将当前的十进制精度设置为 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

也可以使用下面描述的 Context 构造函数创建新的上下文。 此外,该模块还提供了三个预制上下文:

class decimal.BasicContext

这是通用十进制算术规范定义的标准上下文。 精度设置为九。 舍入设置为 ROUND_HALF_UP。 清除所有标志。 除了 InexactRoundedSubnormal 之外,所有陷阱都已启用(视为例外)。

由于启用了许多陷阱,因此此上下文可用于调试。

class decimal.ExtendedContext

这是通用十进制算术规范定义的标准上下文。 精度设置为九。 舍入设置为 ROUND_HALF_EVEN。 清除所有标志。 没有启用陷阱(因此在计算过程中不会引发异常)。

由于陷阱被禁用,此上下文对于更喜欢具有 NaNInfinity 结果值而不是引发异常的应用程序很有用。 这允许应用程序在存在可能停止程序的情况下完成运行。

class decimal.DefaultContext

Context 构造函数使用此上下文作为新上下文的原型。 更改字段(如精度)会更改由 Context 构造函数创建的新上下文的默认值。

此上下文在多线程环境中最有用。 在线程启动之前更改字段之一具有设置系统范围默认值的效果。 不建议在线程启动后更改字段,因为它需要线程同步以防止竞争条件。

在单线程环境中,最好根本不使用此上下文。 相反,只需如下所述显式地创建上下文。

默认值为 prec=28rounding=ROUND_HALF_EVEN,并为 Overflow、InvalidOperation 启用陷阱X141X] 和 DivisionByZero

除了提供的三个上下文之外,还可以使用 Context 构造函数创建新的上下文。

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

创建一个新的上下文。 如果字段未指定或为 None,则从 DefaultContext 复制默认值。 如果 flags 字段未指定或为 None,则清除所有标志。

prec 是 [1, MAX_PREC] 范围内的整数,用于设置上下文中算术运算的精度。

rounding 选项是 Rounding Modes 部分中列出的常量之一。

trapsflags 字段列出了要设置的任何信号。 通常,新上下文应该只设置陷阱并清除标志。

EminEmax 字段是指定指数允许的外部限制的整数。 Emin 必须在 [MIN_EMIN0]、Emax 范围内 [0范围内MAX_EMAX]。

capitals 字段是 01(默认值)。 如果设置为 1,指数以大写 E 打印; 否则,使用小写 eDecimal('6.02e+23')

clamp 字段是 0(默认值)或 1。 如果设置为 1,则在此上下文中可表示的 Decimal 实例的指数 e 严格限制在 Emin - prec + 1 <= e <= Emax - prec + 1 范围内。 如果 clamp0,那么一个较弱的条件成立:Decimal 实例的调整指数至多是 Emax。 当 clamp1 时,一个大的正常数将尽可能减少其指数并在其系数中添加相应数量的零,以适应指数约束; 这会保留数字的值,但会丢失有关重要尾随零的信息。 例如:

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

1clamp 值允许与 IEEE 754 中指定的固定宽度十进制交换格式兼容。

Context 类定义了几个通用方法以及大量直接在给定上下文中进行算术的方法。 此外,对于上述每个 Decimal 方法(adjusted()as_tuple() 方法除外),都有一个对应的 Context 方法. 例如,对于 Context 实例 CDecimal 实例 xC.exp(x) 等价于 x.exp(context=C) . 每个 Context 方法都接受一个 Python 整数(int 的一个实例),只要接受 Decimal 实例。

clear_flags()

将所有标志重置为 0

clear_traps()

将所有陷阱重置为 0

3.3 版中的新功能。

copy()

返回上下文的副本。

copy_decimal(num)

返回 Decimal 实例 num 的副本。

create_decimal(num)

num 创建一个新的 Decimal 实例,但使用 self 作为上下文。 与 Decimal 构造函数不同,上下文精度、舍入方法、标志和陷阱应用于转换。

这很有用,因为常量的精度通常高于应用程序所需的精度。 另一个好处是四舍五入可以立即消除超出当前精度的数字的意外影响。 在以下示例中,使用未舍入的输入意味着将零添加到总和可以更改结果:

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

该方法实现了IBM 规范的to-number 操作。 如果参数是字符串,则不允许前导或尾随空格或下划线。

create_decimal_from_float(f)

从浮点数 f 创建一个新的 Decimal 实例,但使用 self 作为上下文进行舍入。 与 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

3.1 版中的新功能。

Etiny()

返回一个等于 Emin - prec + 1 的值,这是次正规结果的最小指数值。 发生下溢时,指数设置为 Etiny

Etop()

返回一个等于 Emax - prec + 1 的值。

处理小数的常用方法是创建 Decimal 实例,然后应用在活动线程的当前上下文中发生的算术运算。 另一种方法是使用上下文方法在特定上下文中进行计算。 这些方法类似于 Decimal 类的方法,这里只简要介绍。

abs(x)

返回 x 的绝对值。

add(x, y)

返回 xy 的和。

canonical(x)

返回相同的 Decimal 对象 x

compare(x, y)

在数值上比较 xy

compare_signal(x, y)

以数字方式比较两个操作数的值。

compare_total(x, y)

使用抽象表示比较两个操作数。

compare_total_mag(x, y)

使用抽象表示比较两个操作数,忽略符号。

copy_abs(x)

返回符号设置为 0 的 x 的副本。

copy_negate(x)

返回符号反转的 x 的副本。

copy_sign(x, y)

将符号从 y 复制到 x

divide(x, y)

返回 x 除以 y

divide_int(x, y)

返回 x 除以 y,截断为整数。

divmod(x, y)

将两个数字相除并返回结果的整数部分。

exp(x)

返回 e ** x。

fma(x, y, z)

返回 x 乘以 y,再加上 z

is_canonical(x)

如果 x 是规范的,则返回 True; 否则返回 False

is_finite(x)

如果 x 是有限的,则返回 True; 否则返回 False

is_infinite(x)

如果 x 是无限的,则返回 True; 否则返回 False

is_nan(x)

如果 x 是 qNaN 或 sNaN,则返回 True; 否则返回 False

is_normal(x)

如果 x 是正常数,则返回 True; 否则返回 False

is_qnan(x)

如果 x 是一个安静的 NaN,则返回 True; 否则返回 False

is_signed(x)

如果 x 为负,则返回 True; 否则返回 False

is_snan(x)

如果 x 是信号 NaN,则返回 True; 否则返回 False

is_subnormal(x)

如果 x 低于正常值,则返回 True; 否则返回 False

is_zero(x)

如果 x 为零,则返回 True; 否则返回 False

ln(x)

返回 x 的自然(以 e 为底)对数。

log10(x)

返回 x 的以 10 为底的对数。

logb(x)

返回操作数的 MSD 大小的指数。

logical_and(x, y)

在每个操作数的数字之间应用逻辑运算

logical_invert(x)

反转 x 中的所有数字。

logical_or(x, y)

在每个操作数的数字之间应用逻辑运算

logical_xor(x, y)

在每个操作数的数字之间应用逻辑运算 xor

max(x, y)

以数字方式比较两个值并返回最大值。

max_mag(x, y)

以数字方式比较值,忽略其符号。

min(x, y)

以数字方式比较两个值并返回最小值。

min_mag(x, y)

以数字方式比较值,忽略其符号。

minus(x)

减号对应于 Python 中的一元前缀减号运算符。

multiply(x, y)

返回 xy 的乘积。

next_minus(x)

返回小于 x 的最大可表示数。

next_plus(x)

返回大于 x 的最小可表示数字。

next_toward(x, y)

返回最接近 x 的数字,方向为 y

normalize(x)

x 简化为最简单的形式。

number_class(x)

返回 x 类的指示。

plus(x)

加号对应于 Python 中的一元前缀加号运算符。 此操作应用上下文精度和舍入,因此它是 不是 身份操作。

power(x, y, modulo=None)

x 返回到 y 的幂,如果给定,则减少模 modulo

使用两个参数,计算 x**y。 如果 x 为负,则 y 必须是整数。 结果将是不精确的,除非 y 是整数并且结果是有限的并且可以精确地用“精度”数字表示。 使用上下文的舍入模式。 结果在 Python 版本中总是正确四舍五入。

Decimal(0) ** Decimal(0) 导致 InvalidOperation,如果 InvalidOperation 未被捕获,则导致 Decimal('NaN')

3.3 版更改:C 模块根据正确舍入的 exp()ln() 计算 power()职能。 结果是明确定义的,但只是“几乎总是正确四舍五入”。

使用三个参数,计算 (x**y) % modulo。 对于三参数形式,对参数的以下限制成立:

  • 所有三个参数都必须是整数

  • y 必须为非负

  • xy 中的至少一个必须是非零值

  • modulo 必须为非零且最多为“精度”数字


Context.power(x, y, modulo) 产生的值等于通过以无限精度计算 (x**y) % modulo 获得的值,但计算效率更高。 结果的指数为零,与 xymodulo 的指数无关。 结果总是准确的。

quantize(x, y)

返回一个等于 x(四舍五入)的值,其指数为 y

radix()

只返回 10,因为这是十进制,:)

remainder(x, y)

返回整数除法的余数。

结果的符号(如果非零)与原始被除数的符号相同。

remainder_near(x, y)

返回 x - y * n,其中 n 是最接近 x / y 精确值的整数(如果结果为 0,则其符号将是 x 的符号])。

rotate(x, y)

返回 xy 次的旋转副本。

same_quantum(x, y)

如果两个操作数具有相同的指数,则返回 True

scaleb(x, y)

将第二个值与 exp 相加后返回第一个操作数。

shift(x, y)

返回 xy 次的移位副本。

sqrt(x)

非负数的平方根到上下文精度。

subtract(x, y)

返回 xy 之间的差值。

to_eng_string(x)

如果需要指数,则使用工程符号转换为字符串。

工程符号的指数是 3 的倍数。 这最多可以在小数位左侧留下 3 位数字,并且可能需要添加一个或两个尾随零。

to_integral_exact(x)

舍入为整数。

to_sci_string(x)

使用科学记数法将数字转换为字符串。


常数

本节中的常量仅与 C 模块相关。 为了兼容性,它们也包含在纯 Python 版本中。

32 位 64 位
decimal.MAX_PREC
425000000 999999999999999999
decimal.MAX_EMAX
425000000 999999999999999999
decimal.MIN_EMIN
-425000000 -999999999999999999
decimal.MIN_ETINY
-849999999 -1999999999999999997
decimal.HAVE_THREADS
值为 True。 已弃用,因为 Python 现在总是有线程。

自 3.9 版起已弃用。


decimal.HAVE_CONTEXTVAR
默认值为 True。 如果 Python 编译为 --without-decimal-contextvar,则 C 版本使用线程本地而不是协程本地上下文,值为 False。 在某些嵌套上下文场景中,这会稍微快一些。

3.9 版新功能: 向后移植到 3.7 和 3.8。


舍入模式

decimal.ROUND_CEILING
Infinity 舍入。
decimal.ROUND_DOWN
向零舍入。
decimal.ROUND_FLOOR
-Infinity 舍入。
decimal.ROUND_HALF_DOWN
舍入到最接近的关系,并趋向于零。
decimal.ROUND_HALF_EVEN
舍入到最接近的关系到最接近的偶数整数。
decimal.ROUND_HALF_UP
舍入到最接近的关系,从零开始。
decimal.ROUND_UP
从零舍入。
decimal.ROUND_05UP
如果向零舍入后的最后一位数字是 0 或 5,则从零舍入; 否则向零舍入。


信号

信号表示计算过程中出现的条件。 每个对应一个上下文标志和一个上下文陷阱启动器。

每当遇到条件时都会设置上下文标志。 在计算之后,可以出于信息目的检查标志(例如,以确定计算是否准确)。 检查标志后,请务必在开始下一次计算之前清除所有标志。

如果为信号设置了上下文的陷阱启用程序,则该条件会导致引发 Python 异常。 例如,如果设置了 DivisionByZero 陷阱,则在遇到该条件时会引发 DivisionByZero 异常。

class decimal.Clamped

更改了指数以适应表示约束。

通常,当指数超出上下文的 EminEmax 限制时,就会发生钳位。 如果可能,通过向系数添加零来减小指数以适合。

class decimal.DecimalException
其他信号的基类和 ArithmeticError 的子类。
class decimal.DivisionByZero

表示非无限数除以零。

可以与除法、模除法一起发生,或者在将一个数字提高到负幂时发生。 如果该信号未被捕获,则返回 Infinity-Infinity,其符号由计算输入确定。

class decimal.Inexact

表示发生了舍入并且结果不准确。

在舍入期间丢弃非零数字时的信号。 返回四舍五入的结果。 信号标志或陷阱用于检测结果何时不准确。

class decimal.InvalidOperation

执行了无效的操作。

表示请求的操作没有意义。 如果没有被捕获,则返回 NaN。 可能的原因包括:

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

数值溢出。

表示在发生舍入后指数大于 Emax。 如果没有被困,结果取决于舍入模式,要么向内拉到最大的可表示有限数,要么向外舍入到 Infinity。 在任何一种情况下,InexactRounded 也会发出信号。

class decimal.Rounded

尽管可能没有信息丢失,但发生了舍入。

每当舍入丢弃数字时发出信号; 即使这些数字为零(例如将 5.00 舍入为 5.0)。 如果没有被捕获,则返回结果不变。 该信号用于检测有效数字的丢失。

class decimal.Subnormal

在四舍五入之前,指数低于 Emin

当运算结果不正常(指数太小)时发生。 如果没有被捕获,则返回结果不变。

class decimal.Underflow

数值下溢,结果四舍五入为零。

在通过四舍五入将次正规结果推到零时发生。 不精确次正常 也会发出信号。

class decimal.FloatOperation

为混合浮点数和小数启用更严格的语义。

如果信号未被捕获(默认),则允许在 Decimal 构造函数、create_decimal() 和所有比较运算符中混合浮点数和小数。 转换和比较都是精确的。 通过在上下文标志中设置 FloatOperation 来静默记录混合操作的任何发生。 使用 from_float()create_decimal_from_float() 的显式转换不设置标志。

否则(信号被捕获),只有相等比较和显式转换是静默的。 所有其他混合操作引发 FloatOperation

下表总结了信号的层次结构:

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)

浮点注释

以更高的精度减少舍入误差

十进制浮点数的使用消除了十进制表示错误(可以准确表示0.1); 但是,当非零数字超过固定精度时,某些操作仍然会产生舍入误差。

舍入误差的影响可以通过增加或减少几乎抵消的量而放大,从而导致显着性损失。 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')

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')

特殊值

decimal 模块的数字系统提供了特殊值,包括 NaNsNaN-InfinityInfinity 和两个零,[ X143X] 和 -0

无穷大可以直接构造为:Decimal('Infinity')。 此外,当 DivisionByZero 信号未被捕获时,它们可能由除以零引起。 同样,当 Overflow 信号未被捕获时,四舍五入可能会导致超出最大可表示数限制的无穷大。

无穷大是有符号的(仿射),可用于算术运算,将它们视为非常大的不确定数。 例如,向无穷大添加一个常数会得到另一个无穷大的结果。

某些操作不确定并返回 NaN,或者如果 InvalidOperation 信号被捕获,则引发异常。 例如,0/0 返回 NaN,表示“不是数字”。 这种 NaN 是安静的,一旦创建,将通过其他计算始终产生另一个 NaN。 此行为对于偶尔丢失输入的一系列计算很有用 - 它允许计算继续进行,同时将特定结果标记为无效。

一个变体是 sNaN,它在每次操作后发出信号而不是保持安静。 当无效结果需要中断计算以进行特殊处理时,这是一个有用的返回值。

当涉及到 NaN 时,Python 的比较运算符的行为可能有点令人惊讶。 其中一个操作数是安静或信号 NaN 的相等性测试总是返回 False(即使在执行 Decimal('NaN')==Decimal('NaN') 时),而不等性测试总是返回 ]真。 尝试使用 <<=>>= 运算符中的任何一个来比较两个小数将引发 InvalidOperation 信号,如果任一操作数是 NaN,如果该信号未被捕获,则返回 False。 请注意,通用十进制算术规范没有指定直接比较的行为; 这些涉及 NaN 的比较规则取自 IEEE 854 标准(参见第 5.7 节中的表 3)。 为确保严格遵守标准,请改用 compare()compare-signal() 方法。

带符号的零可能来自下溢的计算。 如果计算的精度更高,他们会保留会产生的符号。 由于它们的大小为零,因此正零和负零都被视为相等,并且它们的符号是信息性的。

除了两个不同但相等的有符号零之外,还有各种具有不同精度但值相等的零表示。 这需要一点习惯。 对于习惯于归一化浮点表示的眼睛来说,下面的计算返回一个等于零的值并不是很明显:

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

使用线程

getcontext() 函数为每个线程访问不同的 Context 对象。 拥有单独的线程上下文意味着线程可以在不干扰其他线程的情况下进行更改(例如 getcontext().prec=10)。

同样,setcontext() 函数自动将其目标分配给当前线程。

如果 setcontext()getcontext() 之前没有被调用,那么 getcontext() 将自动创建一个新的上下文以供当前线程使用。

新的上下文是从名为 DefaultContext 的原型上下文中复制的。 要控制默认值以便每个线程在整个应用程序中使用相同的值,请直接修改 DefaultContext 对象。 这应该在 任何线程启动之前完成 ,以便在调用 getcontext() 的线程之间不会出现竞争条件。 例如:

# 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()
 . . .

食谱

以下是一些用作实用函数并演示使用 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.Decimal('1234.5')很麻烦。 有没有办法在使用交互式解释器时尽量减少打字?

  1. 一些用户将构造函数缩写为一个字母:

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

问。 在有两位小数的定点应用中,有些输入有很多位,需要四舍五入。 其他人不应该有多余的数字,需要进行验证。 应该使用哪些方法?

一种。 quantize() 方法四舍五入到固定的小数位数。 如果设置了 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

问。 一旦我有有效的两个地方输入,我如何在整个应用程序中保持不变?

一种。 一些运算,如加法、减法和乘以整数会自动保留不动点。 其他运算,如除法和非整数乘法,会改变小数位数,需要跟上 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')

在开发定点应用时,可以方便地定义处理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')

问。 有很多方法可以表达相同的值。 数字 200200.0002E202E+4 在不同的精度下都具有相同的值。 有没有办法将它们转换为单个可识别的规范值?

一种。 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')]

问。 一些十进制值总是用指数表示法打印。 有没有办法获得非指数表示?

一种。 对于某些值,指数表示法是表示系数中重要位置数的唯一方法。 例如,将 5.0E+3 表示为 5000 可以保持值不变,但不能显示原始的两位重要性。

如果应用程序不关心跟踪重要性,则很容易删除指数和尾随零,失去重要性,但保持值不变:

>>> def remove_exponent(d):
...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
  1. 有没有办法将常规浮点数转换为 十进制

一种。 是的,任何二进制浮点数都可以精确地表示为十进制,尽管精确转换可能比直觉所建议的精度更高:

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

问。 在复杂的计算中,我如何确保我没有因为精度不足或四舍五入异常而得到虚假结果。

一种。 十进制模块使测试结果变得容易。 最佳做法是使用更高的精度和各种舍入模式重新运行计算。 差异很大的结果表明精度不足、舍入模式问题、病态输入或数值不稳定的算法。

问。 我注意到上下文精度应用于操作的结果而不是输入。 混合不同精度的值时有什么需要注意的吗?

一种。 是的。 原则是所有值都被认为是精确的,对这些值的算术也是如此。 只对结果进行四舍五入。 输入的优点是“你输入的就是你得到的”。 一个缺点是,如果您忘记输入尚未四舍五入,结果可能看起来很奇怪:

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

解决方案是提高精度或使用一元加运算强制舍入输入:

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

或者,可以使用 Context.create_decimal() 方法在创建时舍入输入:

>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')
  1. CPython 实现对于大量数据是否快速?

一种。 是的。 在 CPython 和 PyPy3 实现中,十进制模块的 C/CFFI 版本集成了高速 libmpdec 库,用于任意精度的正确舍入十进制浮点运算 1libmpdec 使用 Karatsuba 乘法 处理中等大小的数字,使用 数论变换 处理非常大的数字。

上下文必须适用于精确的任意精度算术。 EminEmax 应始终设置为最大值,clamp 应始终为 0(默认值)。 设置 prec 需要小心。

尝试 bignum 算法的最简单方法是使用 prec2 的最大值:

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

对于不精确的结果,MAX_PREC 在 64 位平台上太大了,可用内存不足:

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

在过度分配的系统上(例如 Linux),更复杂的方法是根据可用 RAM 量调整 prec。 假设您有 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'>]

一般来说(尤其是在没有过度分配的系统上),如果希望所有计算都是准确的,建议估计更严格的界限并设置 不精确 陷阱。

1

3.3 版中的新功能。

2

3.9 版更改: 这种方法现在适用于除非整数幂以外的所有精确结果。