GPU编程 CUDA C++ 随机数生成库 cuRAND库

cuRAND是CUDA中一个和随机数生成有关的库,随机数有伪随机数(pseudorandom numbers)和准随机数(quasirandom number)之分。伪随机数虽然是由某种确定性的算法生成,但它满足大部分真正随机数序列所满足的统计性质。

注意:编译、连接时需要加上 -lcurand 选项

#include <stdio.h>
#include <stdlib.h>
#include <curand.h>   //必须要用到的头文件
void output_results(int N, double *g_x);

int main(void)
{
    curandGenerator_t generator;
    curandCreateGenerator(&generator, CURAND_RNG_PSEUDO_DEFAULT);  //使用CURAND_RNG_PSEUDO_DEFAULT算法生成伪随机数
    curandSetPseudoRandomGeneratorSeed(generator, 1234);    //设置伪随机数种子1234
    int N = 100000;
    double *g_x; cudaMalloc((void **)&g_x, sizeof(double) * N);   //分配GPU数组g_x的显存空间
    curandGenerateUniformDouble(generator, g_x, N);    //产生100000个在0~1之间的均匀分布的双精度浮点型伪随机数,保存于GPU的g_x数组中
    //curandGenerateNormalDouble(generator, g_x, N, 0.0, 1.0);    //产生100000个以0为中心、以1为标准差,呈正态分布的双精度浮点型伪随机数,保存于GPU的g_x数组中
    double *x = (double*) calloc(N, sizeof(double));  //分配主机内存
    cudaMemcpy(x, g_x, sizeof(double) * N, cudaMemcpyDeviceToHost);  //从GPU的g_x复制到主机的x
    cudaFree(g_x);   //释放显存
    output_results(N, x);  //以数组形式打印结果
    free(x);         //释放主机内存
    return 0;
}

void output_results(int N, double *x)
{
    FILE *fid = fopen("x1.txt", "w");    //写模式打开标准文件流,产生一个fid
    for(int n = 0; n < N; n++)
    {
        fprintf(fid, "%g\n", x[n]);      //写入数组元素
    }
    fclose(fid);
}

头文件错误检查函数error.cuh:

#pragma once
#include <stdio.h>

#define CHECK(call)                                   \
{                                                     \
    const cudaError_t error_code = call;              \
    if (error_code != cudaSuccess)                    \
    {                                                 \
        printf("CUDA Error:\n");                      \
        printf("    File:       %s\n", __FILE__);     \
        printf("    Line:       %d\n", __LINE__);     \
        printf("    Error code: %d\n", error_code);   \
        printf("    Error text: %s\n",                \
            cudaGetErrorString(error_code));          \
        exit(1);                                      \
    }                                                 \
}

编译运行:

$ nvcc curand_host1.cu -lcurand -o curand_host1
$ ./curand_host1

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温柔的行子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值