multiprocessing.Value不能正确存储浮点数 [英] multiprocessing.Value doesn't store float correctly
问题描述
我尝试将浮点数分配给multiprocessing.Value共享ctype,如下所示:
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))
但是,存储在multiprocessing.Value中的float是!=输入float:
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
这是什么问题?
找到了解决方案(请参阅答案)但是,我不明白,为什么这里的"double"是正确的类型而不是"float".如果有人可以详细说明并提供解决方案,则将其标记为正确答案.
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.
推荐答案
Python浮点数是double-precision floats
,或其他语言称为double
的浮点数.这就是为什么您需要使用'd'
的原因:'f'
与python用于float
的精度级别不符
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
这篇关于multiprocessing.Value不能正确存储浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!