How to get a “random” number in OpenCL

后端 未结 9 743
悲&欢浪女
悲&欢浪女 2020-12-07 22:59

I\'m looking to get a random number in OpenCL. It doesn\'t have to be real random or even that random. Just something simple and quick.

I see there is a ton of rea

相关标签:
9条回答
  • 2020-12-07 23:15

    This is my version of OpenCL float pseudorandom noise, using trigonometric function

    //noise values in range if 0.0 to 1.0
    static float noise3D(float x, float y, float z) {
        float ptr = 0.0f;
        return fract(sin(x*112.9898f + y*179.233f + z*237.212f) * 43758.5453f, &ptr);
    }
    
    __kernel void fillRandom(float seed, __global float* buffer, int length) {
        int gi = get_global_id(0);
        float fgi = float(gi)/length;
        buffer[gi] = noise3D(fgi, 0.0f, seed);
    }
    

    You can generate 1D or 2D noize by passing to noise3D normalized index coordinates as a first parameters, and the random seed (generated on CPU for example) as a last parameter.

    Here are some noise pictures generated with this kernel and different seeds:

    0 讨论(0)
  • 2020-12-07 23:16

    the following is the algorithm used by the java.util.Random class according to the doc:

    (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
    

    See the documentation for its various implementations. Passing the worker's id in for the seed and looping a few time should produce decent randomness

    or another metod would be to have some random operations occur that are fairly ceratain to overflow:

     long rand= yid*xid*as_float(xid-yid*xid);
     rand*=rand<<32^rand<<16|rand;
     rand*=rand+as_double(rand);
    

    with xid=get_global_id(0); and yid= get_global_id(1);

    0 讨论(0)
  • 2020-12-07 23:16

    It seems OpenCL does not provide such functionality. However, some people have done some research on that and provide BSD licensed code for producing good random numbers on GPU.

    0 讨论(0)
  • 2020-12-07 23:16

    GPU don't have good sources of randomness, but this can be easily overcome by seeding a kernel with a random seed from the host. After that, you just need an algorithm that can work with a massive number of concurrent threads.

    This link describes a Mersenne Twister implementation using OpenCL: Parallel Mersenne Twister. You can also find an implementation in the NVIDIA SDK.

    0 讨论(0)
  • 2020-12-07 23:16

    you cant generate random numbers in kernel , the best option is to generate the random number in host (CPU) and than transfer that to the GPU through buffers and use it in the kernel.

    0 讨论(0)
  • 2020-12-07 23:25

    I had the same problem. www.thesalmons.org/john/random123/papers/random123sc11.pdf

    You can find the documentation here. http://www.thesalmons.org/john/random123/releases/latest/docs/index.html

    You can download the library here: http://www.deshawresearch.com/resources_random123.html

    0 讨论(0)
提交回复
热议问题