什么时候小数被视为 'canonical'?

When is a decimal considered as 'canonical'?

互联网上到处都是说 is_canonical() 方法将 return True 如果十进制是规范的。

但这到底是什么意思?这只是我不知道的一些术语吗?

正如@snakecharmerb 指出的那样,该方法将始终 return True,但我不认为这会使问题变得毫无意义。顺便说一句,为什么方法总是 returns True 可以从方法 canonical():

中看出

Return the canonical encoding of the argument. Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged.

但是,当然,这并没有真正阐明这个主题。但是如果我们查看方法 normalize(),我们会得到一些见解:

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0'). Used for producing canonical values for attributes of an equivalence class. For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent value Decimal('32.1').

上面的描述解释,或多或少规范值是什么。 Also:

Q. There are many ways to express the same value. The numbers 200, 200.000, 2E2, and 02E+4 all have the same value at various precisions. Is there a way to transform them to a single recognizable canonical value?

A. The normalize() method maps all equivalent values to a single representative:

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

canonical 方法的演示

前 3 个 Decimal 值,但不是第 4 个,具有相同的规范表示,因为它们具有相同的值 精度。

>>> from decimal import Decimal
>>>
>>> values = map(Decimal, '2E2 .2E+3 .02E+4 20E1'.split())
>>> [v.canonical() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2.0E+2')]
>>>