使用numpy.savetxt和numpy.loadtxt读写复数

3 投票
1 回答
7780 浏览
提问于 2025-04-18 03:50

我需要写入和读取复数。我想用 numpy.savetxtnumpy.loadtxt 来实现这个功能。因为我写的代码比较复杂,所以我创建了一个测试文件来尝试写入和读取复数。

到目前为止,我已经能够使用 numpy.savetxt 写入复数。我的代码如下:

import numpy

d1 = -0.240921619563 - 0.0303165074169j
d2 = -0.340921619563 - 0.0403165074169j
d3 = -0.440921619563 - 0.0503165074169j
d4 = -0.540921619563 - 0.0603165074169j

array = numpy.array([d1, d2, d3, d4])

save = open("test.dat", "w")
numpy.savetxt(save, array.reshape(1, array.shape[0]), newline = "\r\n", fmt = "%.10f")

save.close()

这段代码的输出结果是:

 (-0.2409216196+-0.0303165074j)  (-0.3409216196+-0.0403165074j)  (-0.4409216196+-0.0503165074j)  (-0.5409216196+-0.0603165074j)

现在我想做的就是实际读取/加载这些数据。我现在的脚本是:

import numpy

d = numpy.loadtxt("test.dat")

这段代码不够用,我目前无法加载数据。我的问题和 这个问题 类似。不过,通过手动将 +- 替换为 -,我仍然无法加载数据。我觉得解决办法在于 numpy.loadtxtdtype 选项,但我还没能搞明白。

非常感谢你的帮助!

1 个回答

6

谢谢你,Warren Weckesser!你推荐的链接对我帮助很大。现在我有两个可以用的脚本:一个是用 numpy.savetxt 写入复数,另一个是用 numpy.loadtxt 从文件中读取/加载复数。

为了以后参考,代码如下。

写入:

import numpy

d1 = -0.240921619563-0.0303165074169j
d2 = -0.340921619563-0.0403165074169j
d3 = -0.440921619563-0.0503165074169j
d4 = -0.540921619563-0.0603165074169j

array = numpy.array([d1, d2, d3, d4])

save = open("test.dat","w")
numpy.savetxt(save, array.reshape(1, array.shape[0]), newline = "\r\n", fmt = '%.4f%+.4fj '*4)

save.close()

读取/加载:

import numpy

coeffs = numpy.loadtxt("test.dat", dtype = numpy.complex128)

撰写回答