Coverage Report

Created: 2026-11-30 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-source/src/nmath/bessel_i.c
Line
Count
Source
1
/*
2
 *  Mathlib : A C Library of Special Functions
3
 *  Copyright (C) 1998-2026 Ross Ihaka and the R Core team.
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
20
/*  DESCRIPTION --> see below */
21
22
23
/* From http://www.netlib.org/specfun/ribesl  Fortran translated by f2c,...
24
 *  ------------------------------=#----  Martin Maechler, ETH Zurich
25
 */
26
#include "nmath.h"
27
#include "bessel.h"
28
29
// set in Rmath.h: #define M_bessel_ik_max_alpha 1e9  -- new (for R 4.7.0)
30
static const double max_alpha_i = M_bessel_ik_max_alpha;
31
32
33
#ifndef MATHLIB_STANDALONE
34
#include <R_ext/Memory.h>
35
#endif
36
37
250
#define min0(x, y) (((x) <= (y)) ? (x) : (y))
38
39
static void I_bessel(double *x, double *alpha, int *nb,
40
         int *ize, double *bi, int *ncalc);
41
42
// in API - Rmath.h -- but *not* called from R ---> rather  bessel_i_ex()  below
43
double bessel_i(double x, double alpha, double expo)
44
0
{
45
0
#ifndef MATHLIB_STANDALONE
46
0
    const void *vmax;
47
0
#endif
48
49
0
#ifdef IEEE_754
50
    /* NaNs propagated correctly */
51
0
    if (ISNAN(x) || ISNAN(alpha)) return x + alpha;
52
0
#endif
53
0
    if (x < 0) {
54
0
  ML_WARNING(ME_RANGE, "bessel_i");
55
0
  return ML_NAN;
56
0
    }
57
0
    int ize = (int)expo;
58
0
    double na = floor(alpha), *bi;
59
0
    if (alpha < 0) {
60
  /* Using Abramowitz & Stegun  9.6.2 & 9.6.6
61
   * this may not be quite optimal (CPU and accuracy wise) */
62
0
  return(bessel_i(x, -alpha, expo) +
63
0
         ((alpha == na) ? /* sin(pi * alpha) = 0 */ 0 :
64
0
    bessel_k(x, -alpha, expo) *
65
0
    ((ize == 1)? 2. : 2.*exp(-2.*x))/M_PI * sinpi(-alpha)));
66
0
    }
67
0
    else if (alpha > max_alpha_i) { // NB: same bound in math_3B() [ ../main/arithmetic.c ]
68
0
  MATHLIB_WARNING2(_("besselI(x, nu): nu=%g > max_alpha_i (= %g): too large for bessel_i() algorithm"),
69
0
       alpha, max_alpha_i);
70
  // FIXME? asymptotic formula (w/ potential accuracy loss) would be better than NaN
71
0
  return ML_NAN;
72
0
    }
73
0
    int ncalc, nb = 1 + (int)na;/* nb-1 <= alpha < nb */
74
0
    alpha -= (double)(nb-1);
75
#ifdef MATHLIB_STANDALONE
76
    bi = (double *) calloc(nb, sizeof(double));
77
    if (!bi) MATHLIB_ERROR("%s", _("bessel_i allocation error"));
78
#else
79
0
    vmax = vmaxget();
80
0
    bi = (double *) R_alloc((size_t) nb, sizeof(double));
81
0
#endif
82
0
    I_bessel(&x, &alpha, &nb, &ize, bi, &ncalc);
83
0
    if(ncalc != nb) {/* error input */
84
0
  if(ncalc < 0)
85
0
      MATHLIB_WARNING4(_("bessel_i(%g): ncalc (=%d) != nb (=%d); alpha=%g. Arg. out of range?\n"),
86
0
           x, ncalc, nb, alpha);
87
0
  else
88
0
      MATHLIB_WARNING2(_("bessel_i(%g,nu=%g): precision lost in result\n"),
89
0
           x, alpha+(double)nb-1);
90
0
    }
91
0
    x = bi[nb-1];
92
#ifdef MATHLIB_STANDALONE
93
    free(bi);
94
#else
95
0
    vmaxset(vmax);
96
0
#endif
97
0
    return x;
98
0
}
99
100
/* modified version of bessel_i() accepting a work array instead of allocating one.
101
   called from R via Math3B() in ../main/arithmetic.c */
102
double bessel_i_ex(double x, double alpha, double expo, double *bi)
103
5.85k
{
104
5.85k
#ifdef IEEE_754
105
    /* NaNs propagated correctly */
106
5.85k
    if (ISNAN(x) || ISNAN(alpha)) return x + alpha;
107
5.85k
#endif
108
5.85k
    if (x < 0) {
109
399
  ML_WARNING(ME_RANGE, "bessel_i");
110
399
  return ML_NAN;
111
399
    }
112
5.45k
    int ize = (int)expo;
113
5.45k
    double na = floor(alpha);
114
5.45k
    if (alpha < 0) {
115
  /* Using Abramowitz & Stegun  9.6.2 & 9.6.6
116
   * this may not be quite optimal (CPU and accuracy wise) */
117
2.04k
  return(bessel_i_ex(x, -alpha, expo, bi) +
118
2.04k
         ((alpha == na) ? 0 :
119
2.04k
    bessel_k_ex(x, -alpha, expo, bi) *
120
1.95k
    ((ize == 1)? 2. : 2.*exp(-2.*x))/M_PI * sinpi(-alpha)));
121
2.04k
    }
122
3.41k
    else if (alpha > max_alpha_i) { // NB: same bound in math_3B() [ ../main/arithmetic.c ]
123
410
  MATHLIB_WARNING2(_("besselI(x, nu): nu=%g > max_alpha_i (= %g): too large for bessel_i() algorithm"),
124
410
       alpha, max_alpha_i);
125
  // FIXME? asymptotic formula (w/ potential accuracy loss) would be better than NaN
126
410
  return ML_NAN;
127
410
    }
128
3.00k
    int ncalc, nb = 1 + (int)na;/* nb-1 <= alpha < nb */
129
3.00k
    alpha -= (double)(nb-1);
130
3.00k
    I_bessel(&x, &alpha, &nb, &ize, bi, &ncalc);
131
3.00k
    if(ncalc != nb) {/* error input */
132
981
  if(ncalc < 0)
133
981
      MATHLIB_WARNING4(_("bessel_i(%g): ncalc (=%d) != nb (=%d); alpha=%g. Arg. out of range?\n"),
134
981
           x, ncalc, nb, alpha);
135
981
  else
136
981
      MATHLIB_WARNING2(_("bessel_i(%g,nu=%g): precision lost in result\n"),
137
981
           x, alpha+(double)nb-1);
138
981
    }
139
3.00k
    x = bi[nb-1];
140
3.00k
    return x;
141
5.45k
}
142
143
static void I_bessel(double *x, double *alpha, int *nb,
144
         int *ize, double *bi, int *ncalc)
145
3.00k
{
146
/* -------------------------------------------------------------------
147
148
 This routine calculates Bessel functions I_(N+ALPHA) (X)
149
 for non-negative argument X, and non-negative order N+ALPHA,
150
 with or without exponential scaling.
151
152
153
 Explanation of variables in the calling sequence
154
155
 X     - Non-negative argument for which
156
   I's or exponentially scaled I's (I*EXP(-X))
157
   are to be calculated.  If I's are to be calculated,
158
   X must be less than exparg_BESS (IZE=1) or xlrg_BESS_IJ (IZE=2),
159
   (see bessel.h).
160
 ALPHA - Fractional part of order for which
161
   I's or exponentially scaled I's (I*EXP(-X)) are
162
   to be calculated.  0 <= ALPHA < 1.0.
163
 NB    - Number of functions to be calculated, NB > 0.
164
   The first function calculated is of order ALPHA, and the
165
   last is of order (NB - 1 + ALPHA).
166
 IZE   - Type.  IZE = 1 if unscaled I's are to be calculated,
167
        = 2 if exponentially scaled I's are to be calculated.
168
 BI    - Output vector of length NB.  If the routine
169
   terminates normally (NCALC=NB), the vector BI contains the
170
   functions I(ALPHA,X) through I(NB-1+ALPHA,X), or the
171
   corresponding exponentially scaled functions.
172
 NCALC - Output variable indicating possible errors.
173
   Before using the vector BI, the user should check that
174
   NCALC=NB, i.e., all orders have been calculated to
175
   the desired accuracy.  See error returns below.
176
177
178
 *******************************************************************
179
 *******************************************************************
180
181
 Error returns
182
183
  In case of an error,  NCALC != NB, and not all I's are
184
  calculated to the desired accuracy.
185
186
  NCALC < 0:  An argument is out of range. For example,
187
     NB <= 0, IZE is not 1 or 2, or IZE=1 and ABS(X) >= EXPARG_BESS.
188
     In this case, the BI-vector is not calculated, and NCALC is
189
     set to MIN0(NB,0)-1 so that NCALC != NB.
190
191
  NB > NCALC > 0: Not all requested function values could
192
     be calculated accurately.  This usually occurs because NB is
193
     much larger than ABS(X).  In this case, BI[N] is calculated
194
     to the desired accuracy for N <= NCALC, but precision
195
     is lost for NCALC < N <= NB.  If BI[N] does not vanish
196
     for N > NCALC (because it is too small to be represented),
197
     and BI[N]/BI[NCALC] = 10**(-K), then only the first NSIG-K
198
     significant figures of BI[N] can be trusted.
199
200
201
 Intrinsic functions required are:
202
203
     DBLE, EXP, gamma_cody, INT, MAX, MIN, REAL, SQRT
204
205
206
 Acknowledgement
207
208
  This program is based on a program written by David J.
209
  Sookne (2) that computes values of the Bessel functions J or
210
  I of float argument and long order.  Modifications include
211
  the restriction of the computation to the I Bessel function
212
  of non-negative float argument, the extension of the computation
213
  to arbitrary positive order, the inclusion of optional
214
  exponential scaling, and the elimination of most underflow.
215
  An earlier version was published in (3).
216
217
 References: "A Note on Backward Recurrence Algorithms," Olver,
218
        F. W. J., and Sookne, D. J., Math. Comp. 26, 1972,
219
        pp 941-947.
220
221
       "Bessel Functions of Real Argument and Integer Order,"
222
        Sookne, D. J., NBS Jour. of Res. B. 77B, 1973, pp
223
        125-132.
224
225
       "ALGORITHM 597, Sequence of Modified Bessel Functions
226
        of the First Kind," Cody, W. J., Trans. Math. Soft.,
227
        1983, pp. 242-245.
228
229
  Latest modification: May 30, 1989
230
231
  Modified by: W. J. Cody and L. Stoltz
232
         Applied Mathematics Division
233
         Argonne National Laboratory
234
         Argonne, IL  60439
235
*/
236
237
    /*-------------------------------------------------------------------
238
      Mathematical constants
239
      -------------------------------------------------------------------*/
240
3.00k
    const static double const__ = 1.585;
241
242
    /* Local variables */
243
3.00k
    int nend, intx, nbmx, k, l, n, nstart;
244
3.00k
    double pold, test,  p, em, en, empal, emp2al, halfx,
245
3.00k
  aa, bb, cc, psave, plast, tover, psavel, sum,
246
247
3.00k
  nu = *alpha,
248
3.00k
  twonu = ldexp(nu, 1); // = 2*nu
249
250
3.00k
    --bi; // use 1-indexing below
251
252
    /*-------------------------------------------------------------------
253
      Check for X, NB, OR IZE out of range.
254
      ------------------------------------------------------------------- */
255
3.00k
    if (*nb > 0 && *x >= 0. && (0. <= nu && nu < 1.) &&
256
3.00k
  (1 <= *ize && *ize <= 2) ) {
257
258
3.00k
  *ncalc = *nb;
259
3.00k
  if(*ize == 1 && *x > exparg_BESS) { // x > 709
260
487M
      for(k=1; k <= *nb; k++)
261
487M
    bi[k]=ML_POSINF; /* the limit *is* = Inf */
262
173
      return;
263
173
  }
264
2.82k
  if(*ize == 2 && *x > xlrg_BESS_IJ) {
265
312M
      for(k=1; k <= *nb; k++)
266
312M
    bi[k]= 0.; /* The limit exp(-x) * I_nu(x) --> 0 : */
267
268
      return;
268
268
  }
269
2.56k
  intx = (int) (*x);/* fine, as long as  *x <= xlrg_BESS_IJ << INT_MAX */
270
2.56k
  if (*x >= rtnsig_BESS) { /* "non-small" x ( >= 1e-4 ) */
271
/* -------------------------------------------------------------------
272
   Initialize the forward sweep, the P-sequence of Olver
273
   ------------------------------------------------------------------- */
274
938
      nbmx = *nb - intx;
275
938
      n = intx + 1;
276
938
      en = (double) (n + n) + twonu;
277
938
      plast = 1.;
278
938
      p = en / *x;
279
      /* ------------------------------------------------
280
         Calculate general significance test
281
         ------------------------------------------------ */
282
938
      test = ensig_BESS + ensig_BESS;
283
938
      if (intx << 1 > nsig_BESS * 5) {
284
113
    test = sqrt(test * p);
285
825
      } else {
286
825
    test /= R_pow_di(const__, intx);
287
825
      }
288
938
      if (nbmx >= 3) {
289
    /* --------------------------------------------------
290
       Calculate P-sequence until N = NB-1
291
       Check for possible overflow.
292
       ------------------------------------------------ */
293
378
    tover = enten_BESS / ensig_BESS;
294
378
    nstart = intx + 2;
295
378
    nend = *nb - 1;
296
59.1k
    for (k = nstart; k <= nend; ++k) {
297
59.0k
        n = k;
298
59.0k
        en += 2.;
299
59.0k
        pold = plast;
300
59.0k
        plast = p;
301
59.0k
        p = en * plast / *x + pold;
302
59.0k
        if (p > tover) {
303
      /* ------------------------------------------------
304
         To avoid overflow, divide P-sequence by TOVER.
305
         Calculate P-sequence until ABS(P) > 1.
306
         ---------------------------------------------- */
307
250
      tover = enten_BESS;
308
250
      p /= tover;
309
250
      plast /= tover;
310
250
      psave = p;
311
250
      psavel = plast;
312
250
      nstart = n + 1;
313
2.45k
      do {
314
2.45k
          ++n;
315
2.45k
          en += 2.;
316
2.45k
          pold = plast;
317
2.45k
          plast = p;
318
2.45k
          p = en * plast / *x + pold;
319
2.45k
      }
320
2.45k
      while (p <= 1.);
321
322
250
      bb = en / *x;
323
      /* ------------------------------------------------
324
         Calculate backward test, and find NCALC,
325
         the highest N such that the test is passed.
326
         ------------------------------------------------ */
327
250
      test = pold * plast / ensig_BESS;
328
250
      test *= .5 - .5 / (bb * bb);
329
250
      p = plast * tover;
330
250
      --n;
331
250
      en -= 2.;
332
250
      nend = min0(*nb,n);
333
1.07k
      for (l = nstart; l <= nend; ++l) {
334
1.06k
          *ncalc = l;
335
1.06k
          pold = psavel;
336
1.06k
          psavel = psave;
337
1.06k
          psave = en * psavel / *x + pold;
338
1.06k
          if (psave * psavel > test) {
339
244
        goto L90;
340
244
          }
341
1.06k
      }
342
6
      *ncalc = nend + 1;
343
250
L90:
344
250
      --(*ncalc);
345
250
      goto L120;
346
6
        }
347
59.0k
    }
348
128
    n = nend;
349
128
    en = (double)(n + n) + twonu;
350
    /*---------------------------------------------------
351
      Calculate special significance test for NBMX > 2.
352
      --------------------------------------------------- */
353
128
    test = fmax2(test,sqrt(plast * ensig_BESS) * sqrt(p + p));
354
128
      }
355
      /* --------------------------------------------------------
356
         Calculate P-sequence until significance test passed.
357
         -------------------------------------------------------- */
358
9.92k
      do {
359
9.92k
    ++n;
360
9.92k
    en += 2.;
361
9.92k
    pold = plast;
362
9.92k
    plast = p;
363
9.92k
    p = en * plast / *x + pold;
364
9.92k
      } while (p < test);
365
366
938
L120:
367
/* -------------------------------------------------------------------
368
 Initialize the backward recursion and the normalization sum.
369
 ------------------------------------------------------------------- */
370
938
      ++n;
371
938
      en += 2.;
372
938
      bb = 0.;
373
938
      aa = 1. / p;
374
938
      em = (double) n - 1.;
375
938
      empal = em + nu;
376
938
      emp2al = em - 1. + twonu;
377
938
      sum = aa * empal * emp2al / em;
378
938
      nend = n - *nb;
379
938
      if (nend < 0) {
380
    /* -----------------------------------------------------
381
       N < NB, so store BI[N] and set higher orders to 0..
382
       ----------------------------------------------------- */
383
223
    bi[n] = aa;
384
223
    nend = -nend;
385
399M
    for (l = 1; l <= nend; ++l) {
386
399M
        bi[n + l] = 0.;
387
399M
    }
388
715
      } else {
389
715
    if (nend > 0) {
390
        /* -----------------------------------------------------
391
           Recur backward via difference equation,
392
           calculating (but not storing) BI[N], until N = NB.
393
           --------------------------------------------------- */
394
395
1.22M
        for (l = 1; l <= nend; ++l) {
396
1.22M
      --n;
397
1.22M
      en -= 2.;
398
1.22M
      cc = bb;
399
1.22M
      bb = aa;
400
      /* for x ~= 1500,  sum would overflow to 'inf' here,
401
       * and the final bi[] /= sum would give 0 wrongly;
402
       * RE-normalize (aa, sum) here -- no need to undo */
403
1.22M
      if(nend > 100 && aa > 1e200) {
404
          /* multiply by  2^-900 = 1.18e-271 */
405
895
          cc  = ldexp(cc, -900);
406
895
          bb  = ldexp(bb, -900);
407
895
          sum = ldexp(sum,-900);
408
895
      }
409
1.22M
      aa = en * bb / *x + cc;
410
1.22M
      em -= 1.;
411
1.22M
      emp2al -= 1.;
412
1.22M
      if (n == 1) {
413
351
          break;
414
351
      }
415
1.22M
      if (n == 2) {
416
442
          emp2al = 1.;
417
442
      }
418
1.22M
      empal -= 1.;
419
1.22M
      sum = (sum + aa * empal) * emp2al / em;
420
1.22M
        }
421
712
    }
422
    /* ---------------------------------------------------
423
       Store BI[NB]
424
       --------------------------------------------------- */
425
715
    bi[n] = aa;
426
715
    if (*nb <= 1) {
427
351
        sum = sum + sum + aa;
428
351
        goto L230;
429
351
    }
430
    /* -------------------------------------------------
431
       Calculate and Store BI[NB-1]
432
       ------------------------------------------------- */
433
364
    --n;
434
364
    en -= 2.;
435
364
    bi[n] = en * aa / *x + bb;
436
364
    if (n == 1) {
437
91
        goto L220;
438
91
    }
439
273
    em -= 1.;
440
273
    if (n == 2)
441
76
        emp2al = 1.;
442
197
    else
443
197
        emp2al -= 1.;
444
445
273
    empal -= 1.;
446
273
    sum = (sum + bi[n] * empal) * emp2al / em;
447
273
      }
448
496
      nend = n - 2;
449
496
      if (nend > 0) {
450
    /* --------------------------------------------
451
       Calculate via difference equation
452
       and store BI[N], until N = 2.
453
       ------------------------------------------ */
454
450k
    for (l = 1; l <= nend; ++l) {
455
449k
        --n;
456
449k
        en -= 2.;
457
449k
        bi[n] = en * bi[n + 1] / *x + bi[n + 2];
458
449k
        em -= 1.;
459
449k
        if (n == 2)
460
420
      emp2al = 1.;
461
449k
        else
462
449k
      emp2al -= 1.;
463
449k
        empal -= 1.;
464
449k
        sum = (sum + bi[n] * empal) * emp2al / em;
465
449k
    }
466
420
      }
467
      /* ----------------------------------------------
468
         Calculate BI[1]
469
         -------------------------------------------- */
470
496
      bi[1] = 2. * empal * bi[2] / *x + bi[3];
471
587
L220:
472
587
      sum = sum + sum + bi[1];
473
474
938
L230:
475
      /* ---------------------------------------------------------
476
         Normalize.  Divide all BI[N] by sum.
477
         --------------------------------------------------------- */
478
938
      if (nu != 0.)
479
852
    sum *= (Rf_gamma_cody(1. + nu) * pow(*x * .5, -nu));
480
938
      if (*ize == 1)
481
411
    sum *= exp(-(*x));
482
938
      aa = enmten_BESS;
483
938
      if (sum > 1.)
484
564
    aa *= sum;
485
399M
      for (n = 1; n <= *nb; ++n) {
486
399M
    if (bi[n] < aa)
487
399M
        bi[n] = 0.;
488
438k
    else
489
438k
        bi[n] /= sum;
490
399M
      }
491
938
      return;
492
1.62k
  } else { /* small x  < 1e-4 */
493
      /* -----------------------------------------------------------
494
         Two-term ascending series for small X.
495
         -----------------------------------------------------------*/
496
1.62k
      aa = 1.;
497
1.62k
      empal = 1. + nu;
498
1.62k
#ifdef IEEE_754
499
      /* No need to check for underflow */
500
1.62k
      halfx = ldexp(*x, -1); // = *x / 2 = .5 * *x
501
#else
502
      if (*x > enmten_BESS) */
503
    halfx = .5 * *x;
504
      else
505
        halfx = 0.;
506
#endif
507
1.62k
      if (nu != 0.)
508
1.47k
    aa = pow(halfx, nu) / Rf_gamma_cody(empal);
509
1.62k
      if (*ize == 2)
510
1.05k
    aa *= exp(-(*x));
511
1.62k
      bb = halfx * halfx;
512
1.62k
      bi[1] = aa + aa * bb / empal;
513
1.62k
      if (*x != 0. && bi[1] == 0.)
514
11
    *ncalc = 0;
515
1.62k
      if (*nb > 1) {
516
1.04k
    if (*x == 0.) {
517
101M
        for (n = 2; n <= *nb; ++n)
518
101M
      bi[n] = 0.;
519
892
    } else {
520
        /* -------------------------------------------------
521
           Calculate higher-order functions.
522
           ------------------------------------------------- */
523
892
        cc = halfx;
524
892
        tover = (enmten_BESS + enmten_BESS) / *x;
525
892
        if (bb != 0.)
526
323
      tover = enmten_BESS / bb;
527
1.06G
        for (n = 2; n <= *nb; ++n) {
528
1.06G
      aa /= empal;
529
1.06G
      empal += 1.;
530
1.06G
      aa *= cc;
531
1.06G
      if (aa <= tover * empal)
532
1.06G
          bi[n] = aa = 0.;
533
3.33k
      else
534
3.33k
          bi[n] = aa + aa * bb / empal;
535
1.06G
      if (bi[n] == 0. && *ncalc > n)
536
726
          *ncalc = n - 1;
537
1.06G
        }
538
892
    }
539
1.04k
      }
540
1.62k
  }
541
2.56k
    } else { /* argument out of range */
542
0
  *ncalc = min0(*nb,0) - 1;
543
0
    }
544
3.00k
}