convert double to float in Python

19,371

Solution 1

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

import struct

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

Solution 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
Share:
19,371
compie
Author by

compie

Updated on July 24, 2022

Comments

  • compie
    compie almost 2 years

    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.

  • jfs
    jfs over 11 years
    @compie: np.float32(v1) == np.float32(v2) or struct.pack("f", v1) == struct.pack("f", v2) == b'\xc8\xf9\xbe\x3b'
  • compie
    compie over 11 years
    I would expect that the two 32-bits floats were exactly (binary) equal ... but apparently they are not, so more has happened with v1 than simply a cast to float.