سؤال

How can I write double precision files binary files using Python? I am doing the following presently but it is giving me single precision files:

#!/usr/bin/env python

import struct

data =[2.3715231753176,9.342983274982732]

output_file = "test.dat"
out_file = open(output_file,"wb")
s = struct.pack('f'*len(data), *data)
out_file.write(s)
out_file.close()
هل كانت مفيدة؟

المحلول

Use d to write double precision floats:

s = struct.pack('d'*len(data), *data)

f is single precision only. See the Format characters section of the struct module documentation:

For the 'f' and 'd' conversion codes, the packed representation uses the IEEE 754 binary32 (for 'f') or binary64 (for 'd') format, regardless of the floating-point format used by the platform.

نصائح أخرى

You're using the format string wrongly. To use double precision, use 'd' instead of 'f'. See the documentation for a list of format characters.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top