Generate Random Inverse Gaussian in R

Needed to generate draws from an inverse Gaussian today, so I wrote the following Rcpp code:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
Col<double> rrinvgauss(int n, double mu, double lambda){

	Col<double> random_vector(n);
	double z,y,x,u;

	for(int i=0; i<n; ++i){
		z=R::rnorm(0,1);
		y=z*z;
		x=mu+0.5*mu*mu*y/lambda - 0.5*(mu/lambda)*sqrt(4*mu*lambda*y+mu*mu*y*y);
		u=R::runif(0,1);
		if(u <= mu/(mu+x)){
			random_vector(i)=x;
		}else{
			random_vector(i)=mu*mu/x;
		};
	}
	return(random_vector);
}

It seems to be faster than existing implementations such as rig from mgcv and rinvgauss from statmod packages.

library(Rcpp) 
library(RcppArmadillo)
library(rbenchmark)
library(statmod)
library(mgcv)
sourceCpp("rrinvgauss.cpp")
n=10000 
benchmark(rig(n,1,1),rinvgauss(n,1,1),rrinvgauss(n,1,1),replications=100)

inverse gaussian

rename rrinvgauss as desired.

  • anspiess

    Nice example for an acceptance-rejection sampler in Rcpp! Two thoughts:
    a) I think you are not using any ARMA function? b) Calling R::rnorm in each iteration should be quite slow, ’cause Rcpp calls an R function which again calls C function ‘C_rnorm’. Could that one be called directly?

    Cheers,
    Andrej

    • admin

      Andrej, the return type Col double (wordpress is formatting the brackets) is defined within Armadillo. I could have used something else but this random number generator is part of a larger project where I use the armadillo library extensively, so I chose it for continuity. If you look at the Writing R Extensions manual you can call the rnorm C function directly if you like, but before you must write GetRNGstate(); and after PutRNGstate();. I assumed that the Rcpp R::rnorm was just doing this all for you.