Convert double to float in Python

In a Python program, I have two values:

v1 = 0.00582811585976 v2 = 0.00582811608911 

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

Details:
The first value is obtained from the hardware board, which calculates with an accuracy of 64 bits. The board transfers the value to the PC, but also needs to convert the value to 32-bit precision and send it to another board, which, in turn, sends it to the PC. I just want to check that this is really happening, and I have two large arrays of numbers.

+4
source share
2 answers

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

 import struct >>> struct.unpack("f", struct.pack("f", 0.00582811585976)) (0.005828116089105606,) 
+9
source

It looks believable:

 >>> 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 
+6
source

Source: https://habr.com/ru/post/1444831/


All Articles