1

Suppose I have a numpy array with some high precision floats obtained from scipy.optimize.minimize, such as: arr = np.array([9.2387213981273981, 0.3219837123801298]). I would like to write this array with this level of precision to a file in a way like the following:

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

However, this doesn't work, since repr(arr) returns 'array([9.2387214 , 0.32198371])', and there is a high level of precision loss here. One potential way to fix this is to convert arr to a list and write the list to the file instead:

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

Here, repr(L) returns '[9.238721398127398, 0.3219837123801298]', and so there is no precision loss. My question is, how can I write the array to a file without converting it to a list, so that the there is no precision loss?

1
  • Text isn't a good format for this purpose. Commented Jul 4, 2021 at 20:56

1 Answer 1

1

You can use np.printoptions context manager and set the precision to, say, 15:

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

after which the file looks like:

from numpy import *
arr = array([9.238721398127398, 0.32198371238013 ])
Sign up to request clarification or add additional context in comments.

1 Comment

(also noting the np.save and np.load functions.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.