convert double to float in Python

2019-04-29 15:21发布

问题:

In a Python program, I have these two values:

v1 = 0.00582811585976
v2 = 0.00582811608911

My hypothesis is that v1 is a 64-bits floating point value, and v2 is v1 converted to a 32-bits floating point value. How can I verify this?

Details:
The first value comes from a hardware board that calculates with 64-bits precision. The board sends the value to a PC, but it should also convert the value to 32-bits precision and send that to another board, which in turn sends it to a PC. I just want to verify that this is really happening and all I have are two large arrays of numbers.

回答1:

You can use the struct module to play with numerical representations:

import struct

>>> struct.unpack("f", struct.pack("f", 0.00582811585976))
(0.005828116089105606,)


回答2:

It looks plausible:

>>> v1 = 0.00582811585976
>>> v2 = 0.00582811608911
>>> import numpy as np
>>> np.float32(v1)
0.0058281161
>>> float(np.float32(v1))  #convert to 32bit and then back to 64bit
0.005828116089105606       #This rounds to v2 if you're printing 14 places of precision ...
>>> '%.14f'%np.float32(v1)
'0.00582811608911'
>>> '%.14f'%np.float32(v1) == '%.14f'%v2
True