gpt4 book ai didi

python - 以工程格式打印编号

转载 作者:太空狗 更新时间:2023-10-29 17:23:54 25 4
gpt4 key购买 nike

我正在尝试使用 python 将数字打印成工程格式,但我似乎无法让它工作。语法 SEEMS 足够简单,但它就是行不通。

>>> import decimal 
>>> x = decimal.Decimal(1000000)
>>> print x
1000000
>>>> print x.to_eng_string()
1000000

我想不通这是为什么。这两个值不相等(一个是字符串,另一个是 int)。在 decimal 中设置各种上下文似乎也无济于事。有什么线索或想法吗?

最佳答案

要让它工作,你必须先规范化小数:

>>> x = decimal.Decimal ('10000000')

>>> x.normalize()
Decimal('1E+7')

>>> x.normalize().to_eng_string()
'10E+6'

可以通过深入研究源代码来发现其原因。

如果你检查 to_eng_string()在 Python 2.7.3 源代码树中(Lib/decimal.py 来自 gzip 源 tar 球 here ),它只是调用 __str__eng设置为真。

然后你可以看到它决定了小数点左边有多少位:

leftdigits = self._exp + len(self._int)

下表显示了这两件事的值:

                         ._exp       ._int         len   leftdigits
----- --------- --- ----------
Decimal (1000000) 0 '1000000' 7 7
Decimal ('1E+6') 6 '1' 1 7

接下来的代码是:

if self._exp <= 0 and leftdigits > -6:
# no exponent required
dotplace = leftdigits
elif not eng:
# usual scientific notation: 1 digit on left of the point
dotplace = 1
elif self._int == '0':
# engineering notation, zero
dotplace = (leftdigits + 1) % 3 - 1
else:
# engineering notation, nonzero
dotplace = (leftdigits - 1) % 3 + 1

你可以看到,除非它已经某个范围内的指数(self._exp > 0 or leftdigits <= -6),否则不会在字符串表示中给它任何指数。


进一步的调查显示了这种行为的原因。查看代码本身,您会发现它基于 General Decimal Arithmetic Specification (PDF here)。

如果您在该文档中搜索 to-scientific-string (to-engineering-string 很大程度上基于此),它部分陈述(释义,并用我的粗体部分):

The "to-scientific-string" operation converts a number to a string, using scientific notation if an exponent is needed. The operation is not affected by the context.

If the number is a finite number then:

The coefficient is first converted to a string in base ten using the characters 0 through 9 with no leading zeros (except if its value is zero, in which case a single 0 character is used).

Next, the adjusted exponent is calculated; this is the exponent, plus the number of characters in the converted coefficient, less one. That is, exponent+(clength-1), where clength is the length of the coefficient in decimal digits.

If the exponent is less than or equal to zero and the adjusted exponent is greater than or equal to -6, the number will be converted to a character form without using exponential notation. In this case, if the exponent is zero then no decimal point is added. Otherwise (the exponent will be negative), a decimal point will be inserted with the absolute value of the exponent specifying the number of characters to the right of the decimal point. “0” characters are added to the left of the converted coefficient as necessary. If no character precedes the decimal point after this insertion then a conventional “0” character is prefixed.

换句话说,它正在做它正在做的事情,因为这是标准要求它做的。

关于python - 以工程格式打印编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12311148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com