round.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* round.c
  2. *
  3. * Round double to nearest or even integer valued double
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * double x, y, round();
  10. *
  11. * y = round(x);
  12. *
  13. *
  14. *
  15. * DESCRIPTION:
  16. *
  17. * Returns the nearest integer to x as a double precision
  18. * floating point result. If x ends in 0.5 exactly, the
  19. * nearest even integer is chosen.
  20. *
  21. *
  22. *
  23. * ACCURACY:
  24. *
  25. * If x is greater than 1/(2*MACHEP), its closest machine
  26. * representation is already an integer, so rounding does
  27. * not change it.
  28. */
  29. /*
  30. Cephes Math Library Release 2.1: January, 1989
  31. Copyright 1984, 1987, 1989 by Stephen L. Moshier
  32. Direct inquiries to 30 Frost Street, Cambridge, MA 02140
  33. */
  34. #include <math.h>
  35. #ifdef ANSIPROT
  36. double floor ( double );
  37. #else
  38. double floor();
  39. #endif
  40. double round(x)
  41. double x;
  42. {
  43. double y, r;
  44. /* Largest integer <= x */
  45. y = floor(x);
  46. /* Fractional part */
  47. r = x - y;
  48. /* Round up to nearest. */
  49. if( r > 0.5 )
  50. goto rndup;
  51. /* Round to even */
  52. if( r == 0.5 )
  53. {
  54. r = y - 2.0 * floor( 0.5 * y );
  55. if( r == 1.0 )
  56. {
  57. rndup:
  58. y += 1.0;
  59. }
  60. }
  61. /* Else round down. */
  62. return(y);
  63. }