产生随机数
cuda产生随机数的程序为
#include <iostream> #include <cuda.h> #include<curand.h> #include<curand_kernel.h> int n = 200; using namespace std; __device__ float generate( curandState* globalState, int ind ) { //int ind = threadIdx.x; curandState localState = globalState[ind]; float RANDOM = curand_uniform( &localState ); globalState[ind] = localState; return RANDOM; } __global__ void setup_kernel ( curandState * state, unsigned long seed ) { int id = threadIdx.x; curand_init ( seed, id, 0, &state[id] ); } __global__ void kernel(float* N, curandState* globalState, int n) { // generate random numbers for(int i=0;i<400;i++) { int k = generate(globalState, i) * 3; while(k > n*n-1) { k-=(n*n-1); } N[i] = k-1; } } int main() { int N=400; curandState* devStates; cudaMalloc ( &devStates, N*sizeof( curandState ) ); // setup seeds setup_kernel <<< 1, N >>> ( devStates,unsigned(time(NULL)) ); float N2[400]; float* N3; cudaMalloc((void**) &N3, sizeof(float)*N); kernel<<<1,1>>> (N3, devStates, n); cudaMemcpy(N2, N3, sizeof(float)*N, cudaMemcpyDeviceToHost); for(int i=0;i<N;i++) { cout<<N2[i]<<endl; } return 0; }
其中400是产生随机数的个数
c++产生随机数的程序为
#include <stdlib.h> #include <stdio.h> #include <time.h> int main() { int i,k; srand( (unsigned)time( NULL ) ); int num_0=0,num_1=0,num_f1; for( i = 0; i < 500000;i++ ) { k=rand() % 3-1;; printf( " k=%d\n", k ); if(k==0){ num_0++; } else if(k==1){ num_1++; }else{ num_f1++; } } printf("%d\n",num_0); printf("%d\n",num_1); printf("%d\n",num_f1); return 0; }