round.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 "mconf.h"
  35. #ifdef ANSIPROT
  36. double floor(double);
  37. #else
  38. double floor();
  39. #endif
  40. double round(x) double x;
  41. {
  42. double y, r;
  43. /* Largest integer <= x */
  44. y = floor(x);
  45. /* Fractional part */
  46. r = x - y;
  47. /* Round up to nearest. */
  48. if (r > 0.5)
  49. goto rndup;
  50. /* Round to even */
  51. if (r == 0.5) {
  52. r = y - 2.0 * floor(0.5 * y);
  53. if (r == 1.0) {
  54. rndup:
  55. y += 1.0;
  56. }
  57. }
  58. /* Else round down. */
  59. return (y);
  60. }