I have many independent random processes (arrival processes say) that require me to generate random numbers. I want to use common random numbers for each of these processes that I can compare how different policies perform when controlling these policies.
I want Process A to be governed by Generator A (using seed A) I want Process B to be governed by Generator B (using seed B) ..
and so on.
Is this possible to implement in R. I can't find anyone who has done it. I have tried. Forgive me if this is a repeated question.
Thanks
Jak
rand() The function rand() is used for random number generator in C in a certain range that can take values from [0, Range_max]. Range_max value can be an integer. It does not take any parameters, and it returns random numbers.
Random Number Generators The default algorithm in R is Mersenne-Twister but a long list of methods is available.
In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.
For uniformly distributed (flat) random numbers, use runif() . By default, its range is from 0 to 1. To generate numbers from a normal distribution, use rnorm() . By default the mean is 0 and the standard deviation is 1.
This is something that I've occassionally wanted to do - and haven't yet come up with much better than the following kludge (which is only really useful if you're using just 1 or 2 different random distributions, as you have to write a function for each:
#Make a list of seeds - generalises to mkore than 2
seed <- list(NA,NA)
set.seed(1)
seed[[1]] <- .Random.seed
set.seed(2)
seed[[2]] <- .Random.seed
my_runif <- function(...,which.seed=1)
{
.Random.seed <<- seed[[which.seed]]
x <-runif(...)
seed[[which.seed]] <<- .Random.seed
x
}
##Print some data for comparison
> set.seed(1); runif(10)
[1] 0.26550866 0.37212390 0.57285336 0.90820779 0.20168193 0.89838968 0.94467527 0.66079779 0.629114040.06178627
> set.seed(2); runif(10)
[1] 0.1848823 0.7023740 0.5733263 0.1680519 0.9438393 0.9434750 0.1291590 0.8334488 0.4680185 0.5499837
#Test
> my_runif(1,which.seed=1)
[1] 0.2655087
> my_runif(1,which.seed=1)
[1] 0.3721239
> my_runif(1,which.seed=1)
[1] 0.5728534
> my_runif(1,which.seed=2)
[1] 0.1848823
> my_runif(1,which.seed=1)
[1] 0.9082078
I'd imagine that the <<-
will break if you call my_runif from inside another function.
fortunes::fortune("<<-")
ETA: The following might be more robust
my_runif <- function(...,which.seed=1)
{
assign(".Random.seed", seed[[which.seed]], envir = .GlobalEnv)
x <-runif(...)
seed <- seed #Bring into local envir
seed[[which.seed]] <- .Random.seed
assign("seed", seed, envir = .GlobalEnv)
x
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With