convert double to float in Python

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!