【问题标题】:Error in string.format using scientific notation with dtype=float32使用 dtype=float32 的科学记数法在 string.format 中出错
【发布时间】:2013-09-17 13:14:59
【问题描述】:

为什么会这样

print "{:e}".format(array([1e-10],dtype="float64")[0])
1.000000e-10

但不是这个?

print "{:e}".format(array([1e-10],dtype="float32")[0])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-9a0800b4df65> in <module>()
----> 1 print "{:e}".format(array([1e-10],dtype="float32")[0])

ValueError: Unknown format code 'e' for object of type 'str

更新: 我尝试使用 numpy 版本 1.6.1 和 Python 2.7.3。

me@serv8:~$ python -V
Python 2.7.3
me@serv8:~$ python -c "import numpy; print numpy.__version__"
1.6.1
me@serv8:~$ python -c "from numpy import array; print \"{:e}\".format(array([1e-10],dtype=\"float32\")[0])"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: Unknown format code 'e' for object of type 'str'

【问题讨论】:

  • 自 1.7.1 起,您使用的是什么版本的 numpy?
  • 两者都适用于 numpy 1.6.2

标签: python numpy


【解决方案1】:

Numpy 错误 #1675

这是一个在 Numpy 1.6.2 (Change log here) 中修复的错误。

分析

嗯...看起来我们可以得到类型了:

>>> from numpy import array
>>> a64 = array([1e-10],dtype="float64")[0]
>>> a32 = array([1e-10],dtype="float32")[0]
>>> type(a32)
<type 'numpy.float32'>
>>> type(a64)
<type 'numpy.float64'>

那么,让我们现在试试打印吧:

>>> print a32
1e-10
>>> print a64
1e-10

好的,这似乎可行。让我们尝试用指数表示法打印:

>>> print('{0:e}'.format(a64))
1.000000e-10
>>> print('{0:e}'.format(a32))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'e' for object of type 'str'

通过谷歌搜索,我发现了与错误 #1675 的类似引用,据说该错误已在 Numpy 版本 1.6.2 中修复。 (Change log here)

基于此,我随后安装了 1.6.2 并尝试了您在上面尝试的方法。有用。

>>> from numpy import array
>>> print "{:e}".format(array([1e-10],dtype="float64")[0])
1.000000e-10
>>> print "{:e}".format(array([1e-10],dtype="float32")[0])
1.000000e-10

【讨论】:

  • 谢谢。但是您是通过哪些 Google 搜索词找到错误报告的?
  • 我使用搜索字符串“python Unknown format code 'e' for object of type 'str'”找到了this answer。但是,它包含指向 projects.scipy.org/numpy/ticket/1675 的死链接。因此,我随后搜索了“numpy bug 1675”,然后帮助我在 sourceforge.net 上找到了更改日志。
  • 该死,我就知道。我本可以自己找到的。再次感谢。
  • 别担心——它会发生 :-)
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多