jn.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. /* jn.c
  2. *
  3. * Bessel function of integer order
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * int n;
  10. * double x, y, jn();
  11. *
  12. * y = jn( 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 range # trials peak rms
  36. * DEC 0, 30 5500 6.9e-17 9.3e-18
  37. * IEEE 0, 30 5000 4.4e-16 7.9e-17
  38. *
  39. *
  40. * Not suitable for large n or x. Use jv() instead.
  41. *
  42. */
  43. /* jn.c
  44. Cephes Math Library Release 2.8: June, 2000
  45. Copyright 1984, 1987, 2000 by Stephen L. Moshier
  46. */
  47. #include <math.h>
  48. #ifdef ANSIPROT
  49. extern double fabs ( double );
  50. extern double j0 ( double );
  51. extern double j1 ( double );
  52. #else
  53. double fabs(), j0(), j1();
  54. #endif
  55. extern double MACHEP;
  56. double jn( n, x )
  57. int n;
  58. double x;
  59. {
  60. 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.0 )
  73. {
  74. if( n & 1 )
  75. sign = -sign;
  76. x = -x;
  77. }
  78. if( n == 0 )
  79. return( sign * j0(x) );
  80. if( n == 1 )
  81. return( sign * j1(x) );
  82. if( n == 2 )
  83. return( sign * (2.0 * j1(x) / x - j0(x)) );
  84. if( x < MACHEP )
  85. return( 0.0 );
  86. /* continued fraction */
  87. #ifdef DEC
  88. k = 56;
  89. #else
  90. k = 53;
  91. #endif
  92. pk = 2 * (n + k);
  93. ans = pk;
  94. xk = x * x;
  95. do
  96. {
  97. pk -= 2.0;
  98. ans = pk - (xk/ans);
  99. }
  100. while( --k > 0 );
  101. ans = x/ans;
  102. /* backward recurrence */
  103. pk = 1.0;
  104. pkm1 = 1.0/ans;
  105. k = n-1;
  106. r = 2 * k;
  107. do
  108. {
  109. pkm2 = (pkm1 * r - pk * x) / x;
  110. pk = pkm1;
  111. pkm1 = pkm2;
  112. r -= 2.0;
  113. }
  114. while( --k > 0 );
  115. if( fabs(pk) > fabs(pkm1) )
  116. ans = j1(x)/pk;
  117. else
  118. ans = j0(x)/pkm1;
  119. return( sign * ans );
  120. }