写作和阅读使用numpy.savetxt和numpy.loadtxt复数 [英] Writing and reading complex numbers using numpy.savetxt and numpy.loadtxt
问题描述
我需要写入和读取复数。我想用 numpy.savetxt
和 numpy.loadtxt
这样做。自从我写了code是相当大的我创建了一个测试文件,试图读写复数。
I need to write and read complex numbers. I would like to use numpy.savetxt
and numpy.loadtxt
to do so. Since the code that I have written is rather big I created a test file to try to write and read complex numbers.
到目前为止,我已经能够使用 numpy.savetxt
编写复杂的数字。在code是以下内容:
So far I have been able to write complex numbers using numpy.savetxt
. The code is the following:
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)
所有的,我现在希望能够做的是实际读取/加载数据。剧本我已经是:
All that I now want to be able to do is actually read/load the data. The script I have is:
import numpy
d = numpy.loadtxt("test.dat")
这件code是不够的,我目前无法加载数据。我的问题是类似这个。但是,通过手动替换 + - 以
A -
我仍然无法加载数据。我认为,解决的办法是为 numpy.loadtxt
的 DTYPE
选项。我一直没能虽然看着办吧。
This piece of code is not sufficient and I am currently unable to load the data. My problem is similar to this one. However, by manually replacing the +-
by a -
I am still unable to load the data. I think the solution lies in the dtype
option for numpy.loadtxt
. I have not been able to figure it out though.
您帮助是极大的AP preciated!
Your help is greatly appreciated!
推荐答案
感谢华伦Weckesser!你建议的链接对我帮助很大。我现在有两个工作的脚本:一个使用 numpy的从文件写入使用
。 numpy.savetxt
复数和一个用于读/加载复数。 loadtxt
Thanks Warren Weckesser! The link you suggested helped me a lot. I now have two working scripts: one for writing complex numbers using numpy.savetxt
and one for reading/loading the complex numbers from the file using numpy.loadtxt
.
对于未来的引用文件,其codeS列举如下。
For future references, the codes are listed below.
写作:
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)
这篇关于写作和阅读使用numpy.savetxt和numpy.loadtxt复数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!