使用 Thomas Wangs 整數雜湊函式
獲取種子並評估的輔助功能:
uint wang_hash(uint seed)
{
seed = (seed ^ 61) ^ (seed >> 16);
seed *= 9;
seed = seed ^ (seed >> 4);
seed *= 0x27d4eb2d;
seed = seed ^ (seed >> 15);
return seed;
}
另一個輔助函式,用它來初始化 id
所示的緩衝區位置:
void wang_rnd_0(__global unsigned int * rnd_buffer,int id)
{
uint maxint=0;
maxint--;
uint rndint=wang_hash(id);
rnd_buffer[id]=rndint;
}
另一個在 0 和 1 之間做額外的浮點輸出
float wang_rnd(__global unsigned int * rnd_buffer,int id)
{
uint maxint=0;
maxint--; // not ok but works
uint rndint=wang_hash(rnd_buffer[id]);
rnd_buffer[id]=rndint;
return ((float)rndint)/(float)maxint;
}
初始化核心:
__kernel void rnd_init(__global unsigned int * rnd_buffer)
{
int id=get_global_id(0);
wang_rnd_0(rnd_buffer,id); // each (id) thread has its own random seed now
}
單迭代核心:
__kernel void rnd_1(__global unsigned int * rnd_buffer)
{
int id=get_global_id(0);
// can use this to populate a buffer with random numbers
// concurrently on all cores of a gpu
float thread_private_random_number=wang_rnd(rnd_buffer,id);
}