# Generating Random Number from inside Kernel

**URL:** <https://discourse.julialang.org/t/generating-random-number-from-inside-kernel/8071>\
**Category:** GPU\
**Created:** [December 30, 2017, 9:19am UTC](https://discourse.julialang.org/t/generating-random-number-from-inside-kernel/8071 "2017-12-30T09:19:19Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![vchuravy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vchuravy/32/8_2.png) [@vchuravy](https://discourse.julialang.org/u/vchuravy)\
**Post date:** [December 30, 2017, 9:46am UTC](https://discourse.julialang.org/t/generating-random-number-from-inside-kernel/8071/2 "2017-12-30T09:46:59Z")

</div>

Yes there are several possibilities. The easiest is probably to use the random number generator that is part of `GPUArrays` should work on the device. (It isn’t documented well, but it should get you started: [https://github.com/JuliaGPU/GPUArrays.jl/blob/master/src/random.jl](https://github.com/JuliaGPU/GPUArrays.jl/blob/master/src/random.jl))

@maleadt wrote this a while back and I don’t think it is part of any repository. It is a `xorshift` implementation.

```julia
function xorshift(x::UInt32)::UInt32
    x = xor(x, x << 13)
    x = xor(x, x >> 17)
    x = xor(x, x << 5)
    return x
end

function gpurand(state::UInt32)::Tuple{Float32,UInt32}
    state = xorshift(state)
    res = (state >> 9) | reinterpret(UInt32, 1f0)
    val = reinterpret(Float32, res) - 1f0
    return val, state
end

function gpu_walk_kernel(f, out, N, x, a, b)
    idx = (blockIdx().x-UInt32(1)) * blockDim().x + threadIdx().x

    # random number generation
    _, state = gpurand(idx)
    function rand()
        let state=state # JuliaLang/julia#15276
            val, state = gpurand(state)
            return val
        end
    end

    ...
end

```

The last idea is to actually use the device version of CURAND.jl and I attempted that in [GitHub - JuliaGPU/CUDAnativelib.jl](https://github.com/JuliaGPU/CUDAnativelib.jl)

---

_[View the full topic](https://discourse.julialang.org/t/generating-random-number-from-inside-kernel/8071)._
