首页 > 解决方案 > 为什么从我的程序中删除多处理会在 math.sin() 函数中引发“需要浮点数”错误?

问题描述

我之前通过多处理实现了我的程序,但现在我使用的是 Numba,所以我想删除多处理。但是,我遇到了一些问题。这里给出了程序的一部分,我使用的是 spyder 版本 3.2.8,它使用的是 python 2.7。

theta = 0
sin_theta = math.sin(math.radians(theta))

多处理实现如下

dataset = []  
for i in range(0, 375, 15):
    for j in range(0, 195, 15):
        for k in range(0, 375, 15):
            dataset.append([i, j, k])


agents = 40
chunksize = 4
pool = mp.Pool(processes = agents)
result = pool.map(calling, dataset, chunksize)

删除多处理后如下

import os
dataset = []  
for i in range(0, 375, 15):
    for j in range(0, 195, 15):
        for k in range(0, 375, 15):
            dataset.append([i, j, k])


calling(dataset)

调用函数是

def calling(dataset):
    l1 = dataset[0]
    l2 = dataset[1]
    l3 = dataset[2]


    import random
    i = random.sample(range(9000), 1)


    t = 0
    f = 0
    z = 0


    global g_r
    global g_o


    g_o_r = grid_one
    global s_a_r, p_l
    rt(p_l, l1, l2, l3, i)

rt 函数是

def rt(p, f, t, z, i):
    import math
    import cmath
    sin_t = math.sin(math.radians(t))
    sin_f = math.sin(math.radians(f))
    sin_z = math.sin(math.radians(z))
    cos_t = math.cos(math.radians(t))
    cos_f = math.cos(math.radians(f))
    cos_z = math.cos(math.radians(z))

错误是

sin_t = math.sin(math.radians(t))
TypeError: a float is required

请告知是否需要任何进一步的信息或数据。

标签: pythonfloating-pointmultiprocessingpython-multiprocessing

解决方案


dataset是一个包含三个元素的列表列表。当使用多处理并通过dataset外部pool.map列表传递时,迭代外部列表并将三元素内部列表传递给calling.

因此,当您这样做时:

l1 = dataset[0]
l2 = dataset[1]
l3 = dataset[2]

l1、l2 和 l3 分别包含内部列表的三个元素之一。

现在您直接传递datasetcalling,l1、l2 和 l3 保存了您的前三个内部列表dataset,所以基本上您传递了列表[0, 0, 0][0, 0, 15]然后传递[0, 0, 30]math.radians(),因此出现错误。

要解决这个问题,只需calling像这样调用:

for inner in dataset:
    calling(inner)

推荐阅读