jnl.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /* jnl.c
  2. *
  3. * Bessel function of integer order
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * int n;
  10. * long double x, y, jnl();
  11. *
  12. * y = jnl( n, x );
  13. *
  14. *
  15. *
  16. * DESCRIPTION:
  17. *
  18. * Returns Bessel function of order n, where n is a
  19. * (possibly negative) integer.
  20. *
  21. * The ratio of jn(x) to j0(x) is computed by backward
  22. * recurrence. First the ratio jn/jn-1 is found by a
  23. * continued fraction expansion. Then the recurrence
  24. * relating successive orders is applied until j0 or j1 is
  25. * reached.
  26. *
  27. * If n = 0 or 1 the routine for j0 or j1 is called
  28. * directly.
  29. *
  30. *
  31. *
  32. * ACCURACY:
  33. *
  34. * Absolute error:
  35. * arithmetic domain # trials peak rms
  36. * IEEE -30, 30 5000 3.3e-19 4.7e-20
  37. *
  38. *
  39. * Not suitable for large n or x.
  40. *
  41. */
  42. /* jn.c
  43. Cephes Math Library Release 2.0: April, 1987
  44. Copyright 1984, 1987 by Stephen L. Moshier
  45. Direct inquiries to 30 Frost Street, Cambridge, MA 02140
  46. */
  47. #include <math.h>
  48. extern long double MACHEPL;
  49. #ifdef ANSIPROT
  50. extern long double fabsl ( long double );
  51. extern long double j0l ( long double );
  52. extern long double j1l ( long double );
  53. #else
  54. long double fabsl(), j0l(), j1l();
  55. #endif
  56. long double jnl( n, x )
  57. int n;
  58. long double x;
  59. {
  60. long double pkm2, pkm1, pk, xk, r, ans;
  61. int k, sign;
  62. if( n < 0 )
  63. {
  64. n = -n;
  65. if( (n & 1) == 0 ) /* -1**n */
  66. sign = 1;
  67. else
  68. sign = -1;
  69. }
  70. else
  71. sign = 1;
  72. if( x < 0.0L )
  73. {
  74. if( n & 1 )
  75. sign = -sign;
  76. x = -x;
  77. }
  78. if( n == 0 )
  79. return( sign * j0l(x) );
  80. if( n == 1 )
  81. return( sign * j1l(x) );
  82. if( n == 2 )
  83. return( sign * (2.0L * j1l(x) / x - j0l(x)) );
  84. if( x < MACHEPL )
  85. return( 0.0L );
  86. /* continued fraction */
  87. k = 53;
  88. pk = 2 * (n + k);
  89. ans = pk;
  90. xk = x * x;
  91. do
  92. {
  93. pk -= 2.0L;
  94. ans = pk - (xk/ans);
  95. }
  96. while( --k > 0 );
  97. ans = x/ans;
  98. /* backward recurrence */
  99. pk = 1.0L;
  100. pkm1 = 1.0L/ans;
  101. k = n-1;
  102. r = 2 * k;
  103. do
  104. {
  105. pkm2 = (pkm1 * r - pk * x) / x;
  106. pk = pkm1;
  107. pkm1 = pkm2;
  108. r -= 2.0L;
  109. }
  110. while( --k > 0 );
  111. if( fabsl(pk) > fabsl(pkm1) )
  112. ans = j1l(x)/pk;
  113. else
  114. ans = j0l(x)/pkm1;
  115. return( sign * ans );
  116. }