我有一个 cuda 应用程序,我想在其中生成 0 到 1 之间的随机数。我编写了一个虚拟代码,其中一个大小为 8x256 的矩阵将被内核生成的随机数填充。我的原始矩阵类似于 8XBIG_NUMBER。但可能我在我的代码中遗漏了一些东西,因为我无法产生想要的结果。我在下面发布我的代码。
void main(int argc,char* argv[])
{
float *test_var,*dev_test;
curandState *state;
test_var = (float *)malloc(8*256*sizeof(float));
memset(test_var,0,8*256*sizeof(float));
cudaMalloc((void **)&dev_test,8*256*sizeof(float));
cudaMemcpy(dev_test,test_var,8*256*sizeof(float),cudaMemcpyHostToDevice);
dim3 gridDim(1,256/32,1);
dim3 blockDim(8,32,1);
cudaMalloc((void **)&state,8*256*sizeof(curandState));
setup_kernel<<<gridDim,blockDim>>>(state,unsigned(time(NULL)));
test_kernel<<<gridDim,blockDim>>>(state,dev_test);
cudaMemcpy(test_var,dev_test,8*256*sizeof(float),cudaMemcpyDeviceToHost);
system("PAUSE");
for (int i=0;i<256;i++)
{ for (int j=0;j<8;j++)
{ printf("%f\t",test_var[i*8+j]);
}
printf("\n");
}
cudaFree(dev_test);
cudaFree(state);
free(test_var);
exit(0);
}
__global__ void setup_kernel(curandState *state,unsigned long seed)
{
int id_col = threadIdx.x + blockDim.x*blockIdx.x;
int id_row = threadIdx.y+blockDim.y*blockIdx.y;
curand_init(seed,(id_row*8+id_col),0,&state[id_row*8+id_col]);
}
__global__ void test_kernel(curandState *state,float *dev_test)
{
int id_col = threadIdx.x + blockDim.x*blockIdx.x;
int id_row = threadIdx.y+blockDim.y*blockIdx.y;
curandState local_state = state[id_row*8+id_col];
dev_test[id_row*8+id_col] = curand(&local_state);
state[id_row*8+id_col] = local_state;
}
我想为矩阵中的每个单元格生成一个介于 0 和 1 之间的随机数。我非常感谢任何人的帮助。谢谢