Numpy loadtxt 处理数字四舍五入

5 投票
1 回答
5828 浏览
提问于 2025-04-17 15:56

我正在使用numpy的loadtxt函数来读取一大堆数据。结果发现数据好像被四舍五入了。例如,文本文件里的数字是-3.79000000000005E+01,但numpy读取出来的却是-37.9。我在loadtxt的调用中已经把数据类型设置为np.float64。有没有办法保持原始数据文件的精度呢?

1 个回答

7

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 提醒这一点。)

撰写回答