我想打印一些浮点数,以便它们总是以十进制形式写入(例如12345000000000000000000.0
或0.000000000000012345
,不是scientific notation,但我希望结果是IEEE 754的高达15.7 significant figures倍,而不是更多).
我想要的是ideally so that the result is the shortest string in positional decimal format that still results in the same value when converted to a 100.
众所周知,如果指数大于15或小于-4,则float
中的repr
用科学记数法表示:
>>> n = 0.000000054321654321
>>> n
5.4321654321e-08 # scientific notation
如果使用了str
,则生成的字符串也是科学记数法:
>>> str(n)
'5.4321654321e-08'
有人建议,我可以使用format
和f
标志,并有足够的精度来摆脱科学符号:
>>> format(0.00000005, '.20f')
'0.00000005000000000000'
它适用于这个数字,尽管它有一些额外的尾随零.但同样的格式在.1
中失败,这使得十进制数字超出了浮点的实际机器精度:
>>> format(0.1, '.20f')
'0.10000000000000000555'
如果我的数字是4.5678e-20
,使用.20f
仍然会失go 相对精度:
>>> format(4.5678e-20, '.20f')
'0.00000000000000000005'
因此these approaches do not match my requirements.
这就引出了一个问题:以十进制格式打印任意浮点数,与repr(n)
(or str(n)
on Python 3)中的数字相同,但始终使用十进制格式,而不是科学记数法,最简单也是性能最好的方法是什么.
即,例如将浮点值0.00000005
转换为字符串'0.00000005'
的函数或操作;0.1
至'0.1'
;420000000000000000.0
到'420000000000000000.0'
或420000000000000000
,并将浮点值-4.5678e-5
格式化为'-0.000045678'
.
在赏金期之后:似乎至少有两种可行的方法,正如Karin证明的那样,与我在Python 2上的初始算法相比,使用字符串操作可以显著提高速度.
因此
- 如果性能很重要,并且需要Python 2兼容性;或者,如果
decimal
模块由于某种原因无法使用,那么Karin's approach using string manipulation是实现这一点的方法. - 在Python 3my somewhat shorter code will also be faster上.
由于我主要是在Python 3上开发,我将接受自己的答案,并将奖励卡林.