PostgreSQL Source Code  git master
rint.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * rint.c
4  * rint() implementation
5  *
6  * By Pedro Gimeno Fortea, donated to the public domain
7  *
8  * IDENTIFICATION
9  * src/port/rint.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 #include "c.h"
14 
15 #include <math.h>
16 
17 /*
18  * Round to nearest integer, with halfway cases going to the nearest even.
19  */
20 double
21 rint(double x)
22 {
23  double x_orig;
24  double r;
25 
26  /* Per POSIX, NaNs must be returned unchanged. */
27  if (isnan(x))
28  return x;
29 
30  if (x <= 0.0)
31  {
32  /* Both positive and negative zero should be returned unchanged. */
33  if (x == 0.0)
34  return x;
35 
36  /*
37  * Subtracting 0.5 from a number very close to -0.5 can round to
38  * exactly -1.0, producing incorrect results, so we take the opposite
39  * approach: add 0.5 to the negative number, so that it goes closer to
40  * zero (or at most to +0.5, which is dealt with next), avoiding the
41  * precision issue.
42  */
43  x_orig = x;
44  x += 0.5;
45 
46  /*
47  * Be careful to return minus zero when input+0.5 >= 0, as that's what
48  * rint() should return with negative input.
49  */
50  if (x >= 0.0)
51  return -0.0;
52 
53  /*
54  * For very big numbers the input may have no decimals. That case is
55  * detected by testing x+0.5 == x+1.0; if that happens, the input is
56  * returned unchanged. This also covers the case of minus infinity.
57  */
58  if (x == x_orig + 1.0)
59  return x_orig;
60 
61  /* Otherwise produce a rounded estimate. */
62  r = floor(x);
63 
64  /*
65  * If the rounding did not produce exactly input+0.5 then we're done.
66  */
67  if (r != x)
68  return r;
69 
70  /*
71  * The original fractional part was exactly 0.5 (since
72  * floor(input+0.5) == input+0.5). We need to round to nearest even.
73  * Dividing input+0.5 by 2, taking the floor and multiplying by 2
74  * yields the closest even number. This part assumes that division by
75  * 2 is exact, which should be OK because underflow is impossible
76  * here: x is an integer.
77  */
78  return floor(x * 0.5) * 2.0;
79  }
80  else
81  {
82  /*
83  * The positive case is similar but with signs inverted and using
84  * ceil() instead of floor().
85  */
86  x_orig = x;
87  x -= 0.5;
88  if (x <= 0.0)
89  return 0.0;
90  if (x == x_orig - 1.0)
91  return x_orig;
92  r = ceil(x);
93  if (r != x)
94  return r;
95  return ceil(x * 0.5) * 2.0;
96  }
97 }
double rint(double x)
Definition: rint.c:21