home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / DBLROUND.HOW < prev    next >
Text File  |  1997-07-05  |  2KB  |  53 lines

  1. +++Date last modified: 05-Jul-1997
  2.  
  3.   Let's look at DBLROUND.C without the #include's or conditional macros for 
  4. NCEG...
  5.  
  6.  
  7. double dround(double x)
  8. {
  9.       Boolean_T flag;
  10.       static volatile double X;
  11.  
  12.       SAVEROUND();
  13.       if (True_ == (flag = (x < 0.0)))
  14.             X = -x;
  15.       else  X = x;
  16.       X += 1.0 / DBL_EPSILON;
  17.       X -= 1.0 / DBL_EPSILON;
  18.       RESTOREROUND();
  19.       return ((flag) ? -X : X);
  20. }
  21.  
  22.  
  23.   The `flag' is obviously there just to keep track of whether `x' is positive 
  24. or negative.
  25.  
  26.   The key to the algorithm is the reciprocal of DBL_EPSILON. Since
  27. DBL_EPSILON is the smallest fractional number which can be represented, its
  28. reciprocal is therefore the smallest number that cannot have a fractional
  29. part. Once you add this reciprocal to `x', its fractional part is stripped
  30. off. Simply subtracting the reciprocal back out returns `x' without its
  31. fractional component.
  32.  
  33.   Simple, clever, and elegant - thanks to Ross Cottrell, the original author.
  34. The additional features added for SNIPPETS include:
  35.  
  36. 1.  The SAVEROUND and RESTOREROUND macros are provided for compilers which
  37.     support the NCEG floating point extensions and provide that for the
  38.     duration of the function, rounding will be performed to the nearest
  39.     value.
  40.  
  41. 2.  An intermediate variable X, declared volatile, is used rather than simply
  42.     using the passed variable x in order to prevent some smart compiler
  43.     optimizer from optimizing the function into oblivion. It's also declared
  44.     static since some compilers will not honor the volatile keyword for an
  45.     auto (stack-based) variable. Since X is declared static, dround() is not
  46.     re-entrant.
  47.  
  48.   All PC compiler vendors use IEEE 754-1985 for their standard floating-point
  49. format. You can get a copy of every standard ever published by IEEE, ANSI,
  50. ISO, API, ASTM, and every other standards organization you can name from
  51. Global Engineering Documents. Be forewarned, however, that they're not cheap.
  52. I think the cheapest standard document I ever got from them was over $50.
  53.