round.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * June 19, 2001 Manuel Novoa III
  3. *
  4. * Replaced cephes round (which was actually round to nearest or even)
  5. * with a (really lame actually) version that always rounds away from 0
  6. * in conformance with ANSI/ISO.
  7. *
  8. * This doesn't check for inf or nan (hence the lame part) but the
  9. * cephes function it replaces didn't either. I plan to deal with
  10. * those issues when I rework things w.r.t. common code.
  11. *
  12. * Also, for now rename the original cephes round routine to rint since
  13. * it behaves the same for the default rounding mode (round to nearest).
  14. * This will have to be changed off course when floating point env
  15. * control functions are added.
  16. */
  17. #include <math.h>
  18. double round(x)
  19. double x;
  20. {
  21. double ax, fax;
  22. ax = fabs(x);
  23. fax = floor(ax);
  24. if (ax - fax >= 0.5) {
  25. fax += 1.0;
  26. }
  27. if (x < 0) {
  28. x = -fax;
  29. } else {
  30. x = fax;
  31. }
  32. return x;
  33. }
  34. /***********************************************************************/
  35. /*
  36. * Returns the nearest integer to x as a double precision
  37. * floating point result. If x ends in 0.5 exactly, the
  38. * nearest even integer is chosen.
  39. */
  40. /*
  41. Originally round from
  42. Cephes Math Library Release 2.1: January, 1989
  43. Copyright 1984, 1987, 1989 by Stephen L. Moshier
  44. Direct inquiries to 30 Frost Street, Cambridge, MA 02140
  45. */
  46. double rint(x)
  47. double x;
  48. {
  49. double y, r;
  50. /* Largest integer <= x */
  51. y = floor(x);
  52. /* Fractional part */
  53. r = x - y;
  54. /* Round up to nearest. */
  55. if( r > 0.5 )
  56. goto rndup;
  57. /* Round to even */
  58. if( r == 0.5 )
  59. {
  60. r = y - 2.0 * floor( 0.5 * y );
  61. if( r == 1.0 )
  62. {
  63. rndup:
  64. y += 1.0;
  65. }
  66. }
  67. /* Else round down. */
  68. return(y);
  69. }