home *** CD-ROM | disk | FTP | other *** search
/ BCI NET 2 / BCI NET 2.iso / archives / programming / source / graphicgems4.lha / GemsIV / dist_fast.c < prev    next >
Encoding:
Text File  |  1995-02-06  |  1.1 KB  |  70 lines

  1. /*
  2.  * C code from the article
  3.  * "Fast Linear Approximations of Euclidean Distance in Higher Dimensions"
  4.  * by Yoshikazu Ohashi, yoshi@cognex.com
  5.  * in "Graphics Gems IV", Academic Press, 1994
  6.  */
  7.  
  8.  
  9. /*
  10.  *    2-D Euclidean distance approximation
  11.  *    c1 = 123/128, c2 = 51 /128 and max(e) = 4.0 %
  12.  *
  13.  */
  14.  
  15. int veclen2 (ix,iy)
  16.      int    ix,iy;
  17. {
  18.   int    t;
  19.  
  20.   ix= (ix<0 ? -ix : ix);    /* absolute values */
  21.   iy= (iy<0 ? -iy : iy);
  22.  
  23.   if(ix<iy)            /* swap ix and iy if (ix < iy) */
  24.   {                /* See Wyvill (G1, 436)           */
  25.     ix=ix^iy;
  26.     iy=ix^iy;
  27.     ix=ix^iy;
  28.   }
  29.  
  30.   t = iy + (iy>>1);
  31.  
  32.   return (ix - (ix>>5) - (ix>>7)  + (t>>2) + (t>>6));
  33. }
  34.  
  35. /*
  36.  *    3-D Euclidean distance approximation
  37.  *    c1 = 15/16 , c2 = c3 = 3/8 and max(e) = 7.7 %
  38.  *
  39.  */
  40.  
  41. int veclen3 (ix,iy,iz)
  42.      int ix,iy,iz;
  43. {
  44.   int    t;
  45.  
  46.   ix= (ix<0 ? -ix : ix);    /* absolute values */
  47.   iy= (iy<0 ? -iy : iy);
  48.   iz= (iz<0 ? -iz : iz);
  49.  
  50.   if(ix<iy)            /* needs only two comparisons */
  51.   {
  52.     ix=ix^iy;
  53.     iy=ix^iy;
  54.     ix=ix^iy;
  55.   }
  56.  
  57.   if(ix<iz)
  58.   {
  59.     ix=ix^iz;
  60.     iz=ix^iz;
  61.     ix=ix^iz;
  62.   }
  63.   /* now ix is the largest */
  64.  
  65.   t = iy + iz;
  66.  
  67.   return (ix - (ix>>4) + (t>>2) + (t>>3));
  68.  
  69. }
  70.