Coverage Report

Created: 2026-11-13 07:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-source/src/nmath/rnchisq.c
Line
Count
Source
1
/*
2
 *  Mathlib : A C Library of Special Functions
3
 *  Copyright (C) 2003--2016 The R Foundation
4
 *
5
 *  This program is free software; you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Public License as published by
7
 *  the Free Software Foundation; either version 2 of the License, or
8
 *  (at your option) any later version.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, a copy is available at
17
 *  https://www.R-project.org/Licenses/
18
 *
19
 *  SYNOPSIS
20
 *
21
 *    #include <Rmath.h>
22
 *    double rnchisq(double df, double lambda);
23
 *
24
 *  DESCRIPTION
25
 *
26
 *    Random variates from the NON CENTRAL chi-squared distribution.
27
 *
28
 *  NOTES
29
 *
30
 According to Hans R. Kuensch's suggestion (30 sep 2002):
31
32
  It should be easy to do the general case (ncp > 0) by decomposing it
33
  as the sum of a central chisquare with df degrees of freedom plus a
34
  noncentral chisquare with zero degrees of freedom (which is a Poisson
35
  mixture of central chisquares with integer degrees of freedom),
36
  see Formula (29.5b-c) in Johnson, Kotz, Balakrishnan (1995).
37
38
  The noncentral chisquare with arbitrary degrees of freedom is of interest
39
  for simulating the Cox-Ingersoll-Ross model for interest rates in
40
  finance.
41
42
  R code that works is
43
44
    rchisq0 <- function(n, ncp) {
45
  p <- 0 < (K <- rpois(n, lambda = ncp / 2))
46
  r <- numeric(n)
47
  r[p] <- rchisq(sum(p), df = 2*K[p])
48
  r
49
    }
50
51
    rchisq <- function(n, df, ncp=0) {
52
  if(missing(ncp)) .Internal(rchisq(n, df))
53
  else rchisq0(n, ncp) + .Internal(rchisq(n, df))
54
    }
55
 */
56
57
#include "nmath.h"
58
59
double rnchisq(double df, double lambda)
60
0
{
61
0
    if (ISNAN(df) || !R_FINITE(lambda) || df < 0. || lambda < 0.)
62
0
  ML_WARN_return_NAN;
63
64
0
    if(lambda == 0.) {
65
0
  return (df == 0.) ? 0. : rgamma(df / 2., 2.);
66
0
    }
67
0
    else {
68
0
  double r = rpois( lambda / 2.);
69
0
  if (r > 0.)  r = rchisq(2. * r);
70
0
  if (df > 0.) r += rgamma(df / 2., 2.);
71
0
  return r;
72
0
    }
73
0
}