1 /* Round according to the current rounding mode.
2 Copyright (C) 2007, 2010-2020 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, see <https://www.gnu.org/licenses/>. */
17 #if ! defined USE_LONG_DOUBLE
29 #ifdef USE_LONG_DOUBLE
31 # define DOUBLE long double
32 # define MANT_DIG LDBL_MANT_DIG
34 # define L_(literal) literal##L
35 #elif ! defined USE_FLOAT
37 # define DOUBLE double
38 # define MANT_DIG DBL_MANT_DIG
40 # define L_(literal) literal
41 #else /* defined USE_FLOAT */
44 # define MANT_DIG FLT_MANT_DIG
46 # define L_(literal) literal##f
49 /* -0.0. See minus-zero.h. */
50 #if defined __hpux || defined __sgi || defined __ICC
51 # define MINUS_ZERO (-MIN * MIN)
53 # define MINUS_ZERO L_(-0.0)
56 /* MSVC with option -fp:strict refuses to compile constant initializers that
57 contain floating-point operations. Pacify this compiler. */
58 #if defined _MSC_VER && !defined __clang__
59 # pragma fenv_access (off)
66 static const DOUBLE TWO_MANT_DIG
=
67 /* Assume MANT_DIG <= 5 * 31.
69 n = floor(n/5) + floor((n+1)/5) + ... + floor((n+4)/5). */
70 (DOUBLE
) (1U << ((MANT_DIG
- 1) / 5))
71 * (DOUBLE
) (1U << ((MANT_DIG
- 1 + 1) / 5))
72 * (DOUBLE
) (1U << ((MANT_DIG
- 1 + 2) / 5))
73 * (DOUBLE
) (1U << ((MANT_DIG
- 1 + 3) / 5))
74 * (DOUBLE
) (1U << ((MANT_DIG
- 1 + 4) / 5));
76 /* The use of 'volatile' guarantees that excess precision bits are dropped at
77 each addition step and before the following comparison at the caller's
78 site. It is necessary on x86 systems where double-floats are not IEEE
79 compliant by default, to avoid that the results become platform and
80 compiler option dependent. 'volatile' is a portable alternative to gcc's
81 -ffloat-store option. */
82 volatile DOUBLE z
= x
;
84 /* Consider the current rounding mode, cf.
85 <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/float.h.html>.
86 This implementation supports only rounds-to-nearest. */
92 /* Avoid rounding error for x = 0.5 - 2^(-MANT_DIG-1). */
95 /* Avoid rounding errors for values near 2^k, where k >= MANT_DIG-1. */
96 else if (z
< TWO_MANT_DIG
)
98 /* Round to the next integer. */
103 else if (z
< L_(0.0))
105 /* Avoid rounding error for x = -(0.5 - 2^(-MANT_DIG-1)). */
108 /* Avoid rounding errors for values near -2^k, where k >= MANT_DIG-1. */
109 else if (z
> -TWO_MANT_DIG
)
111 /* Round to the next integer. */