2013-02-14 99 views
5

我使用numpy loadtxt函数读取一大组数据。数据似乎四舍五入。例如:文本文件中的数字是-3.79000000000005E + 01,但numpy以-37.9读取数字。我已经在loadtxt调用中将dypte设置为np.float64。无论如何要保持原始数据文件的精度?Numpy loadtxt舍入数字

回答

5

loadtxt不是四舍五入的数字。你们看到的是NumPy的选择打印方式数组:

In [80]: import numpy as np 

In [81]: x = np.loadtxt('test.dat', dtype = np.float64) 

In [82]: print(x) 
-37.9 

实际值最接近输入的值np.float64。

In [83]: x 
Out[83]: array(-37.9000000000005) 

或者,你有一个更高维数组中更容易例如,

In [2]: x = np.loadtxt('test.dat', dtype = np.float64) 

如果xrepr看起来截断:

In [3]: x 
Out[3]: array([-37.9, -37.9]) 

可以使用np.set_printoptions获得更高的精度:

In [4]: np.get_printoptions() 
Out[4]: 
{'edgeitems': 3, 
'infstr': 'inf', 
'linewidth': 75, 
'nanstr': 'nan', 
'precision': 8, 
'suppress': False, 
'threshold': 1000} 

In [5]: np.set_printoptions(precision = 17) 

In [6]: x 
Out[6]: array([-37.90000000000050306, -37.90000000000050306]) 

(感谢@mgilson指出这一点。)

+1

它也可能是有益的提['np.set_printoptions'](http://docs.scipy.org/doc/numpy/reference /generated/numpy.set_printoptions.html) – mgilson 2013-02-14 23:20:03

+0

非常好。这解决了这个谜团。更改np.set_printoptions可以打印完整的数字。 – JMD 2013-02-14 23:26:21