1 #include "libm.h"
2 
3 #if FLT_EVAL_METHOD == 0 || FLT_EVAL_METHOD == 1
4 #define EPS DBL_EPSILON
5 #elif FLT_EVAL_METHOD == 2
6 #define EPS LDBL_EPSILON
7 #endif
8 static const double_t toint = 1 / EPS;
9 
round(double x)10 double round(double x) {
11     union {
12         double f;
13         uint64_t i;
14     } u = {x};
15     int e = u.i >> 52 & 0x7ff;
16     double_t y;
17 
18     if (e >= 0x3ff + 52)
19         return x;
20     if (u.i >> 63)
21         x = -x;
22     if (e < 0x3ff - 1) {
23         /* raise inexact if x!=0 */
24         FORCE_EVAL(x + toint);
25         return 0 * u.f;
26     }
27     y = x + toint - toint - x;
28     if (y > 0.5)
29         y = y + x - 1;
30     else if (y <= -0.5)
31         y = y + x + 1;
32     else
33         y = y + x;
34     if (u.i >> 63)
35         y = -y;
36     return y;
37 }
38