
Last chance! 50% off unlimited learning
Sale ends in
Brute-force algorithm for drawing random numbers from a d-dimensional distribution.
rng(f, n, min, max, fmax = NULL, quasi = FALSE, start = 1, warn = TRUE)
Returns list of items:
n-by-d matrix of n random d-vectors.
maximum value of the distribution function f
on the domain.
number of random vectors (same as argument n
).
number of trials.
function of a d-vector representing a d-dimensional distribution function. This function must be non-negative on the whole domain. It does not need to be normalized. For fast performance, this function should be vectorized, such that it returns an N-element vector if it is given an N-by-D matrix as argument. An automatic warning is produced if the function is not vectorized in this manner.
number of random numbers to be generated
are d-vectors specifying the domain of distribution function; the domain must be finite and should be as restrictive as possible to keep the number of random trials as low as possible.
maximum value of f
on its domain. If set to NULL
(default), this value will be determined automatically, using the optimize
(if d=1) and optim
(if d>1) function with its default options. A value for fmax
should be set, if the automatically determined value (see output list) is incorrect.
logical flag. If true, quasi-random numbers with low-discrepancy are drawn, based on a Halton sequence. Otherwise, the standard internal pseudo-random generator of runif()
is used.
starting index of Halton sequence. Only used if quasi=TRUE
.
logical flag. If true, a warning is produced if the function f is not vectorized.
Danail Obreschkow
dpqr
## 1D random number generation from a sine-function
f = function(x) sin(x)
out.pseudo = rng(f,1e3,0,pi)
out.quasi = rng(f,1e3,0,pi,quasi=TRUE)
hist(out.pseudo$x,100,freq=FALSE,border=NA,xlab='x',main='sine-distribution')
hist(out.quasi$x,100,freq=FALSE,border=NA,col='#ff000066',add=TRUE)
curve(sin(x)/2,0,pi,add=TRUE)
## 2D quasi-random sampling of a disk with exponentially declining surface density
f = function(x) exp(-sqrt(x[,1]^2+x[,2]^2))
out = rng(f,1e4,min=c(-5,-5),max=c(5,5),quasi=TRUE)
plot(out$x,cex=0.3,pch=16,asp=1,main='Quasi-random exponential disk')
## 5D random number generation (5-dimensional sphere)
f = function(x) as.numeric(sum(x^2)<=1)
out = rng(f,1e4,rep(-1,5),rep(1,5))
cat(sprintf('Number of successes over number of trials : %.4f\n',out$n/out$ntrials))
cat(sprintf('Expected ratio for n=\u221E : %.4f\n',pi^(5/2)/gamma(1+5/2)/2^5))
Run the code above in your browser using DataLab