我有 numpy array 形式的太大数据和太小数据。和太多的计算。我不想round(num,k)到处都申请。有什么办法可以做一些全局设置来将所有内容四舍五入到小数点后 3 位吗?我使用 Ipython notebook 。
In [1]: import numpy as np
In [2]: np.random.randn(5)
Out[2]: array([-0.15421429, -1.3773473 , 0.89456261, -0.17368004, -0.92570868])
In [3]: np.set_printoptions(precision=3)
In [4]: np.random.randn(5)
Out[4]: array([-0.497, -1.057, -0.638, -0.566, 0.077])
Run Code Online (Sandbox Code Playgroud)
在 IPython 会话中,您还可以使用%precision魔法来做同样的事情:
In [5]: %precision 2
Out[5]: u'%.2f'
In [6]: np.random.randn(5)
Out[6]: array([-1.06, 0.33, -1.8 , 0.74, -0.73])
Run Code Online (Sandbox Code Playgroud)
请注意,这仅影响数字的显示方式- 在幕后,numpynp.double在其计算中仍然使用完整的浮点精度(约 15 位十进制数字)。
OP 似乎对将数组写入具有较少小数位精度的文本文件感兴趣,而不是它们的显示方式。
将 numpy 数组写入文本文件的一种方法是使用np.savetxt. 此函数接受一个fmt参数,它允许您指定任意字符串格式,包括要打印的小数位数。
例如:
x = np.random.randn(10)
# this writes the array out to 6 decimal places
np.savetxt('six_dp.txt', x, fmt='.6f')
# this writes the same array to 3 decimal places
np.savetxt('three_dp.txt', x, fmt='.3f')
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关字符串格式如何在 Python 中工作的更多信息。