| 1 | /* |
| 2 | * ModifiedBesselFirstKind.java |
| 3 | * |
| 4 | * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard |
| 5 | * |
| 6 | * This file is part of BEAST. |
| 7 | * See the NOTICE file distributed with this work for additional |
| 8 | * information regarding copyright ownership and licensing. |
| 9 | * |
| 10 | * BEAST is free software; you can redistribute it and/or modify |
| 11 | * it under the terms of the GNU Lesser General Public License as |
| 12 | * published by the Free Software Foundation; either version 2 |
| 13 | * of the License, or (at your option) any later version. |
| 14 | * |
| 15 | * BEAST is distributed in the hope that it will be useful, |
| 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 18 | * GNU Lesser General Public License for more details. |
| 19 | * |
| 20 | * You should have received a copy of the GNU Lesser General Public |
| 21 | * License along with BEAST; if not, write to the |
| 22 | * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, |
| 23 | * Boston, MA 02110-1301 USA |
| 24 | */ |
| 25 | |
| 26 | package dr.math; |
| 27 | |
| 28 | |
| 29 | import cern.jet.math.Bessel; |
| 30 | |
| 31 | |
| 32 | public class ModifiedBesselFirstKind { |
| 33 | |
| 34 | //Adapted from Numerical Recipes for C |
| 35 | |
| 36 | public static final int ACC = 40; |
| 37 | public static final double BIGNO = 1.0e10; |
| 38 | public static final double BIGNI = 1.0e-10; |
| 39 | |
| 40 | /** |
| 41 | * @param x argument |
| 42 | * @param n order |
| 43 | * @return the modified Bessel function of the first kind and nth order |
| 44 | */ |
| 45 | public static double bessi(double x, int n) { |
| 46 | |
| 47 | if (n == 0) return Bessel.i0(x); |
| 48 | if (n == 1) return Bessel.i1(x); |
| 49 | |
| 50 | int j; |
| 51 | double bi, bim, bip, tox, ans; |
| 52 | |
| 53 | if (x == 0.0) |
| 54 | return 0.0; |
| 55 | else { |
| 56 | tox = 2.0 / Math.abs(x); |
| 57 | bip = ans = 0.0; |
| 58 | bi = 1.0; |
| 59 | for (j = 2 * (n + (int)Math.sqrt(ACC * n)); j > 0; j--) { |
| 60 | bim = bip + j * tox * bi; |
| 61 | bip = bi; |
| 62 | bi = bim; |
| 63 | if (Math.abs(bi) > BIGNO) { |
| 64 | ans *= BIGNI; |
| 65 | bi *= BIGNI; |
| 66 | bip *= BIGNI; |
| 67 | } |
| 68 | if (j == n) ans = bip; |
| 69 | } |
| 70 | ans *= Bessel.i0(x) / bi; |
| 71 | return (x < 0.0 && ((n & 1) != 0)) ? -ans : ans; |
| 72 | } |
| 73 | } |
| 74 | } |