core/vnl/vnl_bessel.cxx
Go to the documentation of this file.
00001 // This is core/vnl/vnl_bessel.cxx
00002 #include "vnl_bessel.h"
00003 #include <vcl_algorithm.h>
00004 
00005 //:
00006 // \file
00007 // \brief Bessel functions of the first kind
00008 // \author Tim Cootes
00009 
00010 //: Compute Bessel functions of first kind up to order n_max.
00011 //  On exit, J[i] = J_i(x) for i=0..n_max
00012 //
00013 // Uses recurrence relation: J_(n-1)(x)+J_(n+1)=(2n/x)J_n(x)
00014 // Thus J_n(x) = (2(n+1)/x)J_(n+1)(x)  - J_(n+2)(x)
00015 // Start with arbitrary guess for high n and work backwards.
00016 // Normalise suitably.
00017 void vnl_bessel(unsigned n_max, double x, vnl_vector<double>& J)
00018 {
00019   if (x==0.0)
00020   {
00021     J.set_size(1+n_max);
00022     J.fill(0.0);
00023     J[0]=1.0;
00024     return;
00025   }
00026   int nhi = 2*((vcl_max(int(n_max),int(x))+15)/2+1);
00027   vnl_vector<double> j(nhi+1);
00028   j[nhi]=0.0;
00029   j[nhi-1]=1.0;
00030   for (int m=nhi-2; m>=0; --m)
00031     j[m]=2*(m+1)*j[m+1]/x - j[m+2];
00032 
00033   // Normalise and return first (1+n_max) values
00034   double sum=j[0];
00035   for (int m=2;m<=nhi;m+=2) sum+=2*j[m];
00036 
00037   J.set_size(1+n_max);
00038   for (unsigned int m=0; m<=n_max; ++m) J[m]=j[m]/sum;
00039 }
00040 
00041 //: Returns J_0(x), the value of the Bessel function of order 0 at x.
00042 //  Bessel function of the first kind of order zero.
00043 //
00044 // Uses recurrence relation: J_(n-1)(x)+J_(n+1)=(2n/x)J_n(x)
00045 double vnl_bessel0(double x)
00046 {
00047   if (x==0) return 1.0;
00048   int nhi = 2*((int(x)+15)/2);  // Even
00049   double j3=0.0;
00050   double j2=1.0;
00051   double j0=j2,j1;
00052   double even_sum=j2;
00053   for (int i=nhi;i>=0;i-=2)
00054   {
00055     // j0 is i-th term, j1 is i+1-th etc
00056     j1=2*(i+2)*j2/x - j3;
00057     j0=2*(i+1)*j1/x - j2;
00058     even_sum+=j0;
00059     j3=j1;
00060     j2=j0;
00061   }
00062   return j0/(2*even_sum-j0);
00063 }
00064 
00065 //: Returns J_n(x), the value of the Bessel function of order n at x.
00066 //  Bessel function of the first kind of order zero.
00067 //
00068 // Uses recurrence relation: J_(n-1)(x)+J_(n+1)=(2n/x)J_n(x)
00069 double vnl_bessel(unsigned n, double x)
00070 {
00071   if (x==0)
00072   {
00073     if (n==0) return 1.0;
00074     else    return 0.0;
00075   }
00076 
00077   int nhi = 2*((vcl_max(int(n),int(x))+15)/2+1);
00078   double j3=0.0;
00079   double j2=1.0;
00080   double j0=j2,j1;
00081   double even_sum=j2;
00082   double jn=j0;
00083   for (int i=nhi; i>=0; i-=2)
00084   {
00085     // j0 is i-th term, j1 is i+1-th etc
00086     j1=2*(i+2)*j2/x - j3;
00087     j0=2*(i+1)*j1/x - j2;
00088     even_sum+=j0;
00089     j3=j1;
00090     j2=j0;
00091     if ((unsigned int)i==n) jn=j0;
00092     else if ((unsigned int)i+1==n) jn=j1;
00093   }
00094   return jn/(2*even_sum-j0);
00095 }