【问题标题】:How can I write a numpy.array to a file and retain all of the digits?如何将 numpy.array 写入文件并保留所有数字?
【发布时间】:2021-09-15 18:20:49
【问题描述】:

假设我有一个 numpy 数组,其中包含一些从 scipy.optimize.minimize 获得的高精度浮点数,例如:arr = np.array([9.2387213981273981, 0.3219837123801298])。我想以这种精度级别的方式将这个数组写入文件,如下所示:

filename = 'parameters.py'
f = open(filename, 'w')
f.write('from numpy import *' + '\n')
f.write('arr = ' + repr(arr))
f.close()

但是,这不起作用,因为repr(arr) 返回'array([9.2387214 , 0.32198371])',并且这里有很高的精度损失。解决此问题的一种可能方法是将arr 转换为列表并将列表写入文件:

L = list(arr)
filename = 'parameters.py'
f = open(filename, 'w')
f.write('L = ' + repr(L))
f.close()

这里,repr(L) 返回'[9.238721398127398, 0.3219837123801298]',因此没有精度损失。我的问题是,如何在不将数组转换为列表的情况下将数组写入文件,从而不存在精度损失?

【问题讨论】:

  • 文本不是用于此目的的好格式。

标签: python arrays numpy repr


【解决方案1】:

您可以使用np.printoptions 上下文管理器并将precision 设置为例如15:

with np.printoptions(precision=15), open(filename, "w") as fh:
    fh.write("from numpy import *\n")
    fh.write("arr = " + repr(arr))

之后文件的样子:

from numpy import *
arr = array([9.238721398127398, 0.32198371238013 ])

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
相关资源
最近更新 更多