multiprocessing.Value 没有正确存储浮点数

multiprocessing.Value doesn't store float correctly

我尝试将浮点数分配给 multiprocessing.Value 共享 ctype,如下所示:

import multiprocessing
import random

test_float = multiprocessing.Value('f', 0)
i = random.randint(1,10000)/(random.randint(1,10000))
test_float.value = i
print("i: type = {}, value = {}".format(type(i), i))
print("test_float: type = {}, value = {}".format(type(test_float.value), test_float.value))
print("i == test_float: {}".format(i == test_float.value))

然而,存储在multiprocessing.Value中的浮点数是!=输入浮点数:

>>> i: type = <class 'float'>, value = 1.480021216407355
>>> test_float: type = <class 'float'>, value = 1.4800212383270264
>>> i == test_float: False

这里有什么问题?

编辑: 找到了解决方案(见答案)但是,我不明白,为什么“double”在这里是正确的类型而不是“float”。如果有人可以详细说明并包含解决方案,我会将其标记为正确答案。

解决方法是将multiprocessing.Valuetypecode_or_type设为double:

test_float = multiprocessing.Value('d', 0)

multiprocessing.Value允许的类型代码:

Type code     C Type          Python Type     Minimum size in bytes
'b'       signed char     int             1
'B'       unsigned char   int             1
'u'       Py_UNICODE      Unicode character 2 (see note)
'h'       signed short    int             2
'H'       unsigned short  int             2
'i'       signed int      int             2
'I'       unsigned int    int             2
'l'       signed long     int             4
'L'       unsigned long   int             4
'f'       float           float           4
'd'       double          float           8

来自 the documentation.

Python 浮点数是 double-precision floats,或者其他语言称为 double 的浮点数。这就是您需要使用 'd' 的原因:'f' 不对应于 python 用于 float

的精度级别