我尝试使用 CUDA 执行 Bessel 函数(例如 J0(x))。这是公式
我尝试将结果控制在某个 epsilon 值内。所以这是代码
__device__ void Bessel_j0(int totalBlocks, int totalThreads, float z, float epsilon, float* result){
int n = 1;
*result = 0;
bool epsilonFlag = true;
int idx_start;
int idx_end;
while(epsilonFlag == true){
initThreadBounds(&idx_start, &idx_end, n, totalBlocks, totalThreads);
float a_k;
for (int k = idx_start; k < idx_end; k++) {
a_k = m_power((-0.25 * z * z), k)/(m_factorial(k) * m_factorial(k));
*result += a_k;
}
if(a_k < epsilon){
epsilonFlag = false;
}
n++;
}
}
__global__ void J0(int totalBlocks, int totalThreads, float x, float* result){
float res = 0;
Bessel_j0(totalBlocks, totalThreads, 10, 0.01, &res);
result[(blockIdx.x*totalThreads + threadIdx.x)] = res;
}
__host__ void J0test(){
const int blocksNum = 32;
const int threadNum = 32;
float *device_resultf; //для устройства
float host_resultf[threadNum*blocksNum] ={0};
cudaMalloc((void**) &device_resultf, sizeof(float)*threadNum*blocksNum);
J0<<<blocksNum, threadNum>>>(blocksNum, threadNum, 10, device_resultf);
cudaThreadSynchronize();
cudaMemcpy(host_resultf, device_resultf, sizeof(float)*threadNum*blocksNum, cudaMemcpyDeviceToHost);
float sum = 0;
for (int i = 0; i != blocksNum*threadNum; ++i) {
sum += host_resultf[i];
printf ("result in %i cell = %f \n", i, host_resultf[i]);
}
printf ("Bessel res = %f \n", sum);
cudaFree(device_resultf);
}
int main(int argc, char* argv[])
{
J0test();
}
当我运行它时出现黑屏并且 Windows 说 nVidia 驱动程序没有响应并且它恢复了它。host_resultf
在控制台输出中,数组中只有零。怎么了?如何在某个 epsilon 内正确执行功能?