这是此代码的改编版,它将产生一组近似“正常”分布的随机数,可以采用大约 0 到 8 之间的离散值。我不明白评论中要求范围为 0 到 8均值为 0。
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>
#include <curand_kernel.h>
#include <math.h>
#define SCALE 2.0
#define SHIFT 4.5
#define DISCRETE
#define BLOCKS 1024
#define THREADS 512
#define CUDA_CALL(x) do { if((x) != cudaSuccess) { \
printf("Error at %s:%d\n",__FILE__,__LINE__); \
return EXIT_FAILURE;}} while(0)
__global__ void setup_kernel(curandState *state)
{
int id = threadIdx.x + blockIdx.x * blockDim.x;
/* Each thread gets different seed, a different sequence
number, no offset */
curand_init(7+id, id, 0, &state[id]);
}
__global__ void generate_normal_kernel(curandState *state,
int *result)
{
int id = threadIdx.x + blockIdx.x * blockDim.x;
float x;
/* Copy state to local memory for efficiency */
curandState localState = state[id];
/* Generate pseudo-random uniforms */
for(int n = 0; n < 10; n++) {
x = (curand_normal(&localState) * SCALE)+SHIFT;
/* Discretize */
#if defined DISCRETE
x = truncf(x);
#endif
}
/* Copy state back to global memory */
state[id] = localState;
/* Store last generated result per thread */
result[id] = (int) x;
}
int main(int argc, char *argv[])
{
int i;
unsigned int total;
curandState *devStates;
int *devResults, *hostResults;
int device;
struct cudaDeviceProp properties;
CUDA_CALL(cudaGetDevice(&device));
CUDA_CALL(cudaGetDeviceProperties(&properties,device));
/* Allocate space for results on host */
hostResults = (int *)calloc(THREADS * BLOCKS, sizeof(int));
/* Allocate space for results on device */
CUDA_CALL(cudaMalloc((void **)&devResults, BLOCKS * THREADS *
sizeof(int)));
/* Set results to 0 */
CUDA_CALL(cudaMemset(devResults, 0, THREADS * BLOCKS *
sizeof(int)));
/* Allocate space for prng states on device */
CUDA_CALL(cudaMalloc((void **)&devStates, THREADS * BLOCKS *
sizeof(curandState)));
/* Setup prng states */
setup_kernel<<<BLOCKS, THREADS>>>(devStates);
/* Generate and use uniform pseudo-random */
generate_normal_kernel<<<BLOCKS, THREADS>>>(devStates, devResults);
/* Copy device memory to host */
CUDA_CALL(cudaMemcpy(hostResults, devResults, BLOCKS * THREADS *
sizeof(int), cudaMemcpyDeviceToHost));
/* Show result */
if (THREADS*BLOCKS > 20){
printf("First 20 stored results:\n");
for (i=0; i<20; i++)
printf("%d\n", hostResults[i]);
}
total = 0;
for(i = 0; i < BLOCKS * THREADS; i++) {
total += hostResults[i];
}
printf("Results mean = %f\n", (total/(1.0*BLOCKS*THREADS)));
/* Cleanup */
CUDA_CALL(cudaFree(devStates));
CUDA_CALL(cudaFree(devResults));
free(hostResults);
return EXIT_SUCCESS;
}
您也可以轻松修改此代码以生成连续值正态分布(浮点数)。
正态分布的两个参数是均值和标准差。这些使用 SHIFT 和 SCALE 参数表示。SHIFT 将平均值从零移动。SCALE 修改标准偏差(从 1.0,到 SCALE 指示的任何值)。因此,您可以使用 SHIFT 和 SCALE 参数来获得您想要的分布。请注意,随机数生成器的实值输出的截断会影响统计信息。您可以通过调整 SCALE 或 SHIFT 来对此进行调整,或者您可以从truncf()
, 切换到某种形式的舍入。
你可以编译这个:
nvcc -arch=sm_20 -o uniform uniform.cu
假设您有 cc2.0 或更高版本的 GPU。
如果没有,可以编译:
nvcc -o uniform uniform.cu
在这种情况下,编译器警告 double 被降级为 float 是可以忽略的。
THREADS
并且BLOCKS
是机器范围内的任意选择。您可以修改这些以适合您自己代码的特定启动配置。