[R-SIG-Finance] bug in rnig (Rmetrics: fBasics 251.70)

Martin Becker martin.becker at mx.uni-saarland.de
Mon Aug 13 11:22:13 CEST 2007


Dear maintainers/users of Rmetrics,


the random generator for NIG random variates (rnig) in fBasics version 
251.70 (and probably prior versions) is faulty, which is easily 
visualised, e.g., by the following code:

  library(fBasics)
  curve(dnig(x,alpha=4,beta=1,delta=3),-2,4)
  lines(density(rnig(n=100000,alpha=4,beta=1,delta=3)),col="red")

The bug is caused by a minor error in the PhD thesis of S. Raible 
(2000), which is the source of the current implementation of rnig.
Please find below a patch for 2B-HyperbolicDistribution.R (which besides 
changes three apparently nonessential global assignments to local ones) 
as well as a documentation patch (for 2B-HyperbolicDistribution.Rd), 
which includes references to a correct implementation.


Kind regards,

   Martin Becker



diff --recursive fBasics.orig/R/2B-HyperbolicDistribution.R 
fBasics/R/2B-HyperbolicDistribution.R
1372,1374c1372,1374
<         z1 <<- function(v, delta, gamma) {
<             delta/gamma + v/(gamma^2) - sqrt( 2*v*delta/(gamma^3) +
<             (v/(gamma^2))^2 )
---
 >         z1 <- function(v, delta, gamma) {
 >             delta/gamma + v/(2*gamma^2) - sqrt( v*delta/(gamma^3) +
 >             (v/(2*gamma^2))^2 )
1376c1376
<         z2 <<- function(v, delta, gamma) {
---
 >         z2 <- function(v, delta, gamma) {
1379c1379
<         pz1 <<- function(v, delta, gamma) {
---
 >         pz1 <- function(v, delta, gamma) {

diff --recursive fBasics.orig/man/2B-HyperbolicDistribution.Rd 
fBasics/man/2B-HyperbolicDistribution.Rd
173,174c173,177
<     The random deviates are calculated with the method described by
<     Raible (2000).
---
 >     The generator \code{rnig} is based on general methods given by
 >     Michael et al. (1976), as implemented in, e.g., Benth et al. 
(2006) for
 >     the case of NIG random variates.
 >     \emph{Caution: up to fBasics v251.70, \code{rnig} was based on the
 >     incorrect implementation described by Raible (2000).}
203a207,216
 > Benth F.E., Groth M., Kettler P.C. (2006);
 >     \emph{A Quasi-Monte Carlo Algorithm for the Normal Inverse Gaussian
 >     Distribution and Valuation of Financial Derivatives},
 >     International Journal of Theoretical and Applied Finance, 9(6), 
843--867.
 >
 > Michael J.R., Schucany W.R., Haas R.W. (1976);
 >     \emph{Generating Random Variates Using Transformations with Multiple
 >     Roots},
 >     The American Statistician, 30(2), 88--90.
 >



More information about the R-SIG-Finance mailing list