openCL 内核计算 Pi 的值不正确

openCL Kernel to calculate Pi is not correct value

美好的一天,

我有一个使用莱布尼茨公式计算 pi 的 openCL 内核。目前我的问题是我得到的值不是 pi,而是 4。

__kernel void calculatePi(int numIterations, __global float *outputPi,
                          __local float* local_result, int numWorkers)
{
    __private const uint gid = get_global_id(0);
    __private const uint lid = get_local_id(0);
    __private const uint offset = numIterations*gid*2; 
    __private float sum = 0.0f;

    // Have the first worker initialize local_result
    if (gid == 0)
    {
        for (int i = 0; i < numWorkers; i++)
        {
            local_result[i] = 0.0f;
        }
    }

    // Have all workers wait until this is completed
    barrier(CLK_GLOBAL_MEM_FENCE);

    // Have each worker calculate their portion of pi
    // This is a private value
    for (int i=0; i<numIterations; i++) 
    {
        if (i % 2 == 0)
        {
            sum += 1 / (1 + 2*i + offset);
        }
        else
        {
            sum -= 1 / (1 + 2*i + offset);
        }
    }

    // Have each worker move their value to the appropriate
    // local_result slot so that the first worker can see it
    // when reducing next
    local_result[gid] = sum;    

    // Make sure all workers complete this task before continuing
    barrier(CLK_LOCAL_MEM_FENCE);

    // Have the first worker add up all of the other worker's values
    // to get the final value
    if (lid == 0)
    {
        outputPi[0] = 0;
        for (int i = 0; i < numWorkers; i++)
        {
            outputPi[0] += local_result[i]; 
        }

        outputPi[0] *= 4;
    }    
}

我已将所有输入引导至输出,以验证它们是否符合我的预期。 numIterations 是 16 并且 numWorkers 也是 16.

当计算第一个工人的总和时,我希望总和是 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + 1/17 - 1/19 + 1/21 - 1/23 + 1/25 - 1/27 + 1/29 - 1/31

前 16 次使用此计算器,我预计结果在 3.2 左右:https://scratch.mit.edu/projects/19546118/

如果我将我的最后一段代码修改成这样,这样我就可以查看工人的计算值 "sum":

    // Have the first worker add up all of the other worker's values
    // to get the final value
    if (lid == 0)
    {
        outputPi[0] = sum * 4;
    } 

然后为第一个工人返回的值是 4 而不是预期的 3.2

修改为除 lid == 0 以外的任何其他数字,所有其他工作人员都报告他们的总和为 0。所以我的问题是为什么计算值是这样?我的 sum 变量有问题吗?这应该是一个私有变量,根据我对每个工人的理解,for 循环应该是顺序的,但是许多循环是根据工人的数量并行执行的。

这是我的 github 的一个 link 已经上传了内核和主要代码。

https://github.com/TreverWagenhals/TreverWagenhals/tree/master/School/Heterogeneous%20Computing/Lab2

谢谢

您在代码中进行整数除法,应该是浮点数:

if (i % 2 == 0)
{
   sum += 1. / (1 + 2*i + offset); // notice the 1.
}
else
{
   sum -= 1. / (1 + 2*i + offset);
}