jnf.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /* jnf.c
  2. *
  3. * Bessel function of integer order
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * int n;
  10. * float x, y, jnf();
  11. *
  12. * y = jnf( 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. * IEEE 0, 15 30000 3.6e-7 3.6e-8
  37. *
  38. *
  39. * Not suitable for large n or x. Use jvf() instead.
  40. *
  41. */
  42. /* jn.c
  43. Cephes Math Library Release 2.2: June, 1992
  44. Copyright 1984, 1987, 1992 by Stephen L. Moshier
  45. Direct inquiries to 30 Frost Street, Cambridge, MA 02140
  46. */
  47. #include <math.h>
  48. extern float MACHEPF;
  49. float j0f(float), j1f(float);
  50. float jnf( int n, float xx )
  51. {
  52. float x, pkm2, pkm1, pk, xk, r, ans, xinv, sign;
  53. int k;
  54. x = xx;
  55. sign = 1.0;
  56. if( n < 0 )
  57. {
  58. n = -n;
  59. if( (n & 1) != 0 ) /* -1**n */
  60. sign = -1.0;
  61. }
  62. if( n == 0 )
  63. return( sign * j0f(x) );
  64. if( n == 1 )
  65. return( sign * j1f(x) );
  66. if( n == 2 )
  67. return( sign * (2.0 * j1f(x) / x - j0f(x)) );
  68. /*
  69. if( x < MACHEPF )
  70. return( 0.0 );
  71. */
  72. /* continued fraction */
  73. k = 24;
  74. pk = 2 * (n + k);
  75. ans = pk;
  76. xk = x * x;
  77. do
  78. {
  79. pk -= 2.0;
  80. ans = pk - (xk/ans);
  81. }
  82. while( --k > 0 );
  83. /*ans = x/ans;*/
  84. /* backward recurrence */
  85. pk = 1.0;
  86. /*pkm1 = 1.0/ans;*/
  87. xinv = 1.0/x;
  88. pkm1 = ans * xinv;
  89. k = n-1;
  90. r = (float )(2 * k);
  91. do
  92. {
  93. pkm2 = (pkm1 * r - pk * x) * xinv;
  94. pk = pkm1;
  95. pkm1 = pkm2;
  96. r -= 2.0;
  97. }
  98. while( --k > 0 );
  99. r = pk;
  100. if( r < 0 )
  101. r = -r;
  102. ans = pkm1;
  103. if( ans < 0 )
  104. ans = -ans;
  105. if( r > ans ) /* if( fabs(pk) > fabs(pkm1) ) */
  106. ans = sign * j1f(x)/pk;
  107. else
  108. ans = sign * j0f(x)/pkm1;
  109. return( ans );
  110. }