Skip to contents

local_nv_rng_state() and with_nv_rng_state() make rng_state the random state the samplers draw from, for the calling scope or for code only, and restore the one from before afterwards. The draws advance rng_state in place. In a function traced by jit(), they cannot be called in the body of nv_while() or nv_scan(): called before the loop, they reach its body.

See the Random Number Generation article for more details.

Usage

local_nv_rng_state(rng_state, envir = parent.frame())

with_nv_rng_state(rng_state, code)

Arguments

rng_state

(AnvlRngState)
The random state to draw from, as nv_rng_state() returns.

envir

(environment)
The scope whose exit restores the default from before.

code

(any)
An expression to evaluate drawing from rng_state.

Value

local_nv_rng_state() returns NULL, invisibly; with_nv_rng_state() returns the result of evaluating code.

Examples

rng <- nv_rng_state(1L)
with_nv_rng_state(rng, list(nv_runif(2L), nv_rnorm(2L)))
#> [[1]]
#> AnvlArray
#>  0.7026
#>  0.2348
#> [ CPUf32{2} ] 
#> 
#> [[2]]
#> AnvlArray
#>  -0.3611
#>  -0.9505
#> [ CPUf32{2} ] 
#> 
# both samplers drew from `rng`, three sampling calls in all
rng
#> <AnvlRngState> key 0x0000000000000001, counter 0x0000000000000003

# in a jitted function, from a random state it takes as an argument
step <- jit(function(x, rng) {
  local_nv_rng_state(rng)
  x + nv_rnorm(2L) + nv_runif(2L)
})
step(nv_array(c(0, 0)), rng)
#> AnvlArray
#>  -0.4693
#>   0.1911
#> [ CPUf32{2} ] 
rng
#> <AnvlRngState> key 0x0000000000000001, counter 0x0000000000000006