2
2
* Mathlib : A C Library of Special Functions
3
3
* Copyright (C) 1998 Ross Ihaka
4
4
* Copyright (C) 2000-8 The R Development Core Team
5
* Copyright (C) 2004 The R Foundation
5
* Copyright (C) 2004-8 The R Foundation
7
7
* This program is free software; you can redistribute it and/or modify
8
8
* it under the terms of the GNU General Public License as published by
32
32
const static double eps = 5e-15;
34
double i, ncp2, q, mid, dfmid, imax, errorbound;
34
double i, ncp2, q, mid, dfmid, imax;
50
50
return dchisq(x, df, give_log);
51
if(x == ML_POSINF) return R_D__0;
54
55
/* find max element of sum */
55
56
imax = ceil((-(2+df) +sqrt((2-df) * (2-df) + 4 * ncp * x))/4);
56
57
if (imax < 0) imax = 0;
57
dfmid = df + 2 * imax;
58
mid = dpois_raw(imax, ncp2, FALSE) * dchisq(x, dfmid, FALSE);
59
dfmid = df + 2 * imax;
60
mid = dpois_raw(imax, ncp2, FALSE) * dchisq(x, dfmid, FALSE);
61
} else /* imax = Inf */
65
/* underflow to 0 -- maybe numerically correct; maybe can be more accurate,
66
* particularly when give_log = TRUE */
67
/* Use central-chisq approximation formula when appropriate;
68
* ((FIXME: the optimal cutoff also depends on (x,df); use always here? )) */
69
if(give_log || ncp > 1000.) {
70
double nl = df + ncp, ic = nl/(nl + ncp);/* = "1/(1+b)" Abramowitz & St.*/
71
return dchisq(x*ic, nl*ic, give_log);
78
/* errorbound := term * q / (1-q) now subsumed in while() / if() below: */
81
term = mid; df = dfmid; i = imax;
67
84
q = x * ncp2 / i / df;
71
errorbound = term * q / (1-q);
72
} while (errorbound > eps || q >= 1);
88
} while (q >= 1 || term * q > (1-q)*eps);
90
term = mid; df = dfmid; i = imax;
79
93
q = i * df / x / ncp2;
83
errorbound = term * q / (1-q);
84
if (errorbound <= eps && q < 1) break;
97
if (q < 1 && term * q <= (1-q)*eps) break;
86
99
return R_D_val(sum);