gpt4 book ai didi

c - openCL 内核计算 Pi 的值不正确

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:45 24 4
gpt4 key购买 nike

你好,

我有一个使用莱布尼茨公式计算 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。

当计算第一个 worker 的总和时,我希望总和为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;
}

然后返回给第一个 worker 的值是 4 而不是预期的 3.2

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

这是我的 github 链接,其中已上传内核和主要代码。

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

谢谢

最佳答案

您在代码中执行积分除法,应该是 float :

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

关于c - openCL 内核计算 Pi 的值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53398186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com