【发布时间】:2021-03-23 23:58:44
【问题描述】:
我正在编写一份教学文档,该文档使用大量 Python 代码示例并包含生成的数字输出。我在 IPython 内部工作,很多示例都使用 NumPy。
我想避免打印语句、显式格式或类型转换。它们使示例变得混乱,并有损于我试图解释的原则。
我知道的:
-
在 IPython 中,我可以使用
%precision来控制任何float结果的显示精度。 -
我可以使用
np.set_printoptions()来控制元素的显示精度在 NumPy 数组中。
我正在寻找的是一种控制 NumPy float64 标量的显示精度的方法,它不响应上述任何一个。这些由许多 NumPy 函数返回。
>>> x = some_function()
Out[2]: 0.123456789
>>> type(x)
Out[3]: numpy.float64
>>> %precision 2
Out[4]: '%.2f'
>>> x
Out[5]: 0.123456789
>>> float(x) # that precision works for regular floats
Out[6]: 0.12
>>> np.set_printoptions(precision=2)
>>> x # but doesn't work for the float64
Out[8]: 0.123456789
>>> np.r_[x] # does work if it's in an array
Out[9]: array([0.12])
我想要的是
>>> # some formatting command
>>> x = some_function() # that returns a float64 = 0.123456789
Out[2]: 0.12
但我愿意接受:
- 一种告诉 NumPy 默认给我
float标量的方法,而不是float64。 - 一种告诉 IPython 如何处理
float64的方法,有点像我可以为自己的课程使用repr_pretty做的事情。
【问题讨论】:
-
x.item()有帮助吗? -
@hpaulj 是的,但不超过
float(x),这可能更具描述性。但是.item()可以添加到末尾,而不必包装表达式。
标签: numpy format ipython precision float64