3

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.

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() 

This gives the following output:

 (-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") 

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.

Your help is greatly appreciated!

3
  • 1
    See if this helps: stackoverflow.com/questions/21012484/… Commented Apr 22, 2014 at 23:06
  • Is there a specific reason why you want to use loadtxt and savetxt rather than just load and save or tofile and fromfile? Commented Apr 22, 2014 at 23:21
  • Isn't this a bug in numpy? In my opinion savetxt should provide a correctly formatted complex numbers... Commented Jan 2, 2015 at 9:40

1 Answer 1

6

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.

For future references, the codes are listed below.

Writing:

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() 

Reading/Loading:

import numpy coeffs = numpy.loadtxt("test.dat", dtype = numpy.complex128) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.