multiprocessing.Value doesn't store float corr

2020-04-24 17:05发布

问题:

I try to asign a float to the multiprocessing.Value shared ctype as follows:

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))

However, the float stored in multiprocessing.Value is != the input float:

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

Whats the problem here?

EDIT: Found the solution (see answers) However, I do not understand, why a "double" is the correct type here and not a "float". If someone can elaborate on that and include the solution, I will mark it as the correct answer.

回答1:

Python floats are double-precision floats, or what other languages would call double's. That is why you need to use 'd': 'f' does not correspond to the precision level python uses for float's



回答2:

The solution is to set the typecode_or_type of multiprocessing.Value to be a double:

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

Allowed typecodes for 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

From the documentation.