CUDA:实现模拟梅森旋转算法
下面是一个使用 CUDA 实现模拟梅森旋转算法(Mersenne Twister)生成随机数的示例代码:
#include <iostream>
#include <cuda_runtime.h>
#include <curand_kernel.h>
#define THREADS_PER_BLOCK 256
#define NUM_BLOCKS 30
#define NUM_SAMPLES (THREADS_PER_BLOCK * NUM_BLOCKS)
__global__ void initMT(curandState *state, unsigned long long seed) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
curand_init(seed, tid, 0, &state[tid]);
}
__global__ void generateRandomNumbers(curandState *state, float *randomNumbers) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
randomNumbers[tid] = curand_uniform(&state[tid]);
}
int main() {
// Allocate memory for random numbers on device
float *d_randomNumbers;
cudaMalloc(&d_randomNumbers, sizeof(float